package com.huadao.cart_ccs.experiment.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseActivity;
import com.huadao.cart_ccs.common.ByteUtils;
import com.huadao.cart_ccs.common.ExperimentStageManager;
import com.huadao.cart_ccs.common.ParamsPreferences;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.deviceController.CO2Controller;
import com.huadao.cart_ccs.common.deviceController.CirculatingPumpController;
import com.huadao.cart_ccs.common.deviceController.O2Controller;
import com.huadao.cart_ccs.common.deviceController.TemperatureController;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.common.dialog.IDialogResultListener;
import com.huadao.cart_ccs.common.inputControl.NumberMaxAttention;
import com.huadao.cart_ccs.common.popwindow.RockPop;
import com.huadao.cart_ccs.data.bean.EnvironmentLog;
import com.huadao.cart_ccs.data.bo.ChangeLiquidAmount;
import com.huadao.cart_ccs.data.bo.ExperimentStage;
import com.huadao.cart_ccs.data.bo.PeristalticPumpBO;
import com.huadao.cart_ccs.data.task.ChangeLiquidBO;
import com.huadao.cart_ccs.data.task.LiquidLoopTask;
import com.huadao.cart_ccs.experiment.addCell.AddCellDF;
import com.huadao.cart_ccs.experiment.addViruses.AddVirusesDF;
import com.huadao.cart_ccs.experiment.adjustTemperature.AdjustTemperatureDF;
import com.huadao.cart_ccs.experiment.adjustWeight.AdjustWeightDF;
import com.huadao.cart_ccs.experiment.changeLiquidDialog.ChangeLiquidTXDF;
import com.huadao.cart_ccs.experiment.changeLiquidPlan.ChangeLiquidPlanListFrag;
import com.huadao.cart_ccs.experiment.cleanPipes.CleanPipesDF;
import com.huadao.cart_ccs.experiment.concentrationReplacement.ConcentrationReplacementDF;
import com.huadao.cart_ccs.experiment.confirmBeforeCulture.rawMaterial.RawMaterialDF;
import com.huadao.cart_ccs.experiment.confirmBeforeCulture.rawMaterial.RawMaterialFrag;
import com.huadao.cart_ccs.experiment.internalControl.InternalControlDF;
import com.huadao.cart_ccs.experiment.liquidControl.LiquidControlDF;
import com.huadao.cart_ccs.experiment.log.LogDF;
import com.huadao.cart_ccs.experiment.paramsSetting.ParamConsts;
import com.huadao.cart_ccs.experiment.paramsSetting.SetParamsDF;
import com.huadao.cart_ccs.experiment.preprocessing.PreProcessingActivity;
import com.huadao.cart_ccs.experiment.progressOverview.ProgressOverViewDF;
import com.huadao.cart_ccs.experiment.sample.SampleDF;
import com.huadao.cart_ccs.experiment.sterilization.UltravioletSterilizationActivity;
import com.huadao.cart_ccs.experiment.test.ConsoleFrag;
import com.huadao.cart_ccs.experiment.test.ForceTestDF;
import com.huadao.cart_ccs.greendao.entity.DeviceRecord;
import com.huadao.cart_ccs.greendao.entity.Operation;
import com.huadao.cart_ccs.greendao.entity.Sample;
import com.huadao.cart_ccs.main.CartApplication;
import com.huadao.cart_ccs.widget.WaveView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class ExperimentActivity extends BaseActivity implements ExperimentContract.IExperimentView, SampleDF.OnSample, NumberMaxAttention, LiquidControlDF.LiquidControl, AddCellDF.OnAddCell, AddVirusesDF.OnAddViruses {
    @BindView(R.id.tv_CO2)
    TextView tvCO2;
    @BindView(R.id.tv_O2)
    TextView tvO2;
    @BindView(R.id.tv_temperature)
    TextView tvTemperature;
    @BindView(R.id.frag_console)
    FrameLayout frameLayout;
    @BindView(R.id.gif_pump_fluidIntake)
    GifImageView gifPumpFluidIntake;
    @BindView(R.id.tv_pump_fluidIntake_state)
    TextView tvPumpFluidIntakeState;
    @BindView(R.id.gif_pump_waste)
    GifImageView gifPumpWaste;
    @BindView(R.id.tv_pump_circulating_state)
    TextView tvPumpCirculatingState;
    @BindView(R.id.gif_pump_circulating)
    GifImageView gifPumpCirculating;
    @BindView(R.id.tv_pump_waste_state)
    TextView tvPumpWasteState;
    @BindView(R.id.gif_pump_reclaim)
    GifImageView gifPumpReclaim;
    @BindView(R.id.tv_pump_reclaim_state)
    TextView tvPumpReclaimState;
    //    @BindView(R.id.btn_start_culture)
//    Button btn_start_culture;
//    @BindView(R.id.UltravioletLight)
//    ImageView UltravioletLight;
//    @BindView(R.id.btn_pause_culture)
//    Button btn_pause_culture;
//    @BindView(R.id.btn_resume_culture)
//    Button btn_resume_culture;
    //    @BindView(R.id.btn_terminate_culture)
//    Button btn_terminate_culture;
    @BindView(R.id.tv_stirrer_state)
    TextView tvStirrerState;
    @BindView(R.id.gif_Incubator)
    GifImageView gif_Incubator;
    @BindView(R.id.gif_cultureTank)
    GifImageView gif_cultureTank;
    @BindView(R.id.gif_magnetic_stirrer)
    GifImageView gif_magnetic_stirrer;
    @BindView(R.id.tv_cultureTank_state)
    TextView tvCultureTankState;
    @BindView(R.id.iv_O2_warning)
    ImageView iv_O2_warning;
    @BindView(R.id.iv_CO2_warning)
    ImageView iv_CO2_warning;
    @BindView(R.id.iv_temperature_warning)
    ImageView iv_temperature_warning;
    @BindView(R.id.UltravioletLight_wick)
    ImageView UltravioletLight_wick;
    @BindView(R.id.tv_level_warning)
    TextView tv_level_warning;
    @BindView(R.id.tv_weight)
    TextView tv_weight;
    @BindView(R.id.progressBar1)
    ProgressBar progressBar1;
    @BindView(R.id.progressBar2)
    ProgressBar progressBar2;
    @BindView(R.id.progressBar3)
    ProgressBar progressBar3;
    @BindView(R.id.progressBar4)
    ProgressBar progressBar4;
    @BindView(R.id.tv_fluidIntake_countdown)
    TextView tv_fluidIntake_countdown;
    @BindView(R.id.tv_discharge_countdown)
    TextView tv_discharge_countdown;
    @BindView(R.id.tv_collect_countdown)
    TextView tv_collect_countdown;
    @BindView(R.id.tv_changeLiquid_countdown)
    TextView tv_changeLiquid_countdown;
    @BindView(R.id.btn_door)
    Button btn_door;
    @BindView(R.id.btn_sample)
    TextView btnSample;
//    @BindView(R.id.btn_inject)
//    Button btnInject;
//    @BindView(R.id.btn_after_culture)
//    Button btn_after_culture;

    @BindView(R.id.rl_materialConfirm)
    RelativeLayout rlMaterialConfirm;
    @BindView(R.id.rl_defaultParams)
    RelativeLayout rlDefaultParams;
    @BindView(R.id.rl_cleanPipe)
    RelativeLayout rlCleanPipe;
    @BindView(R.id.rl_input_liquid)
    RelativeLayout rlInputLiquid;
    @BindView(R.id.rl_sample)
    RelativeLayout rlSample;
    @BindView(R.id.rl_add_cell)
    RelativeLayout rlAddCell;
    @BindView(R.id.rl_add_viruses)
    RelativeLayout rlAddViruses;
    @BindView(R.id.rl_ConcentrationReplacement)
    RelativeLayout rlConcentrationReplacement;
    @BindView(R.id.rl_addCryoprotectant)
    RelativeLayout rlAddCryoprotectant;
    @BindView(R.id.rl_material_kill)
    RelativeLayout rlMaterialKill;
    @BindView(R.id.rl_cleanConfirm)
    RelativeLayout rlCleanConfirm;
    @BindView(R.id.rl_UV_disinfection)
    RelativeLayout rlUVDisinfection;
    @BindView(R.id.rl_fluidIntake)
    RelativeLayout rlFluidIntake;
    @BindView(R.id.rl_discharge)
    RelativeLayout rlDischarge;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    @BindView(R.id.rl_changeLiquid)
    RelativeLayout rlChangeLiquid;
    //    @BindView(R.id.tv_electronic_scal)
//    TextView tv_electronic_scal;
    @BindView(R.id.btn_add_cell)
    TextView btn_add_cell;
    @BindView(R.id.btn_add_viruses)
    TextView btn_add_viruses;
    //    @BindView(R.id.spinner_recycle)
//    Spinner spinner_recycle;
//    @BindView(R.id.SalineReplacementMedium)
//    Button SalineReplacementMedium;
    @BindView(R.id.addCryoprotectant)
    TextView addCryoprotectant;
    @BindView(R.id.cleanConfirm)
    TextView cleanConfirm;
    @BindView(R.id.UV_disinfection)
    TextView UV_disinfection;
    @BindView(R.id.btn_materialConfirm)
    TextView btn_materialConfirm;
    @BindView(R.id.btn_defaultParams)
    TextView btn_defaultParams;
    @BindView(R.id.btn_cleanPipe)
    TextView btn_cleanPipe;
    @BindView(R.id.btn_input_liquid)
    TextView btn_input_liquid;
    @BindView(R.id.iv_next)
    FrameLayout iv_next;
    @BindView(R.id.iv_finish_culture)
    FrameLayout iv_finish_culture;
    @BindView(R.id.btn_ConcentrationReplacement)
    TextView btn_ConcentrationReplacement;
    @BindView(R.id.btn_material_kill)
    TextView btn_material_kill;
    @BindView(R.id.iv_finish_collect)
    FrameLayout iv_finish_collect;
    @BindView(R.id.tv_referenceWeight)
    TextView tv_referenceWeight;
    @BindView(R.id.split_fluidIntake)
    View split_fluidIntake;
    @BindView(R.id.split_changeLiquid)
    View split_changeLiquid;
    @BindView(R.id.btn_fluidIntake)
    TextView btn_fluidIntake;
    @BindView(R.id.btn_discharge)
    TextView btn_discharge;
    @BindView(R.id.btn_collect)
    TextView btn_collect;
    @BindView(R.id.btn_changeLiquid)
    TextView btn_changeLiquid;
    @BindView(R.id.addCryoprotectantLoading)
    ImageView addCryoprotectantLoading;
    @BindView(R.id.concentrationReplacementLoading)
    ImageView concentrationReplacementLoading;
    @BindView(R.id.changeLiquidLoading)
    ImageView changeLiquidLoading;
    @BindView(R.id.collectLoading)
    ImageView collectLoading;
    @BindView(R.id.dischargeLoading)
    ImageView dischargeLoading;
    @BindView(R.id.fluidIntakeLoading)
    ImageView fluidIntakeLoading;
    @BindView(R.id.inputLiquidLoading)
    ImageView inputLiquidLoading;
    @BindView(R.id.cleanPipeLoading)
    ImageView cleanPipeLoading;
    @BindView(R.id.wv_tank)
    WaveView wv_tank;

    //    private View home;
//    private View log;
//    private View setting;
    private TextView tv_title;

    private final byte[] lock_FluidIntake = new byte[1];
    private final byte[] lock_Waste = new byte[1];
    private final byte[] lock_Circulating = new byte[1];
    private final byte[] lock_Reclaim = new byte[1];

    private GifDrawable gifD_FluidIntake;
    private GifDrawable gifD_Waste;
    private GifDrawable gifD_Circulating;
    private GifDrawable gifD_Reclaim;
    private GifDrawable gifDIncubator;
    private GifDrawable gifDCultureTank;
    private GifDrawable gifDMagneticStirrer;

    private FragmentManager fragmentManager;
    private ExperimentPresenter presenter;
    //标记取样前是否在运行，如果是则取样后恢复运行
    private boolean isIntakeNeedResumeAfterSample;
    private boolean isWasteNeedResumeAfterSample;
    private boolean isCircleNeedResumeAfterSample;
    private boolean isReclaimNeedResumeAfterSample;
    private boolean isSampling;
    private boolean isAddCell;
    private boolean isAddViruses;
//    private boolean isInjecting;

    private SampleDF sampleDF;
    private AddCellDF addCellDF;
    private AddVirusesDF addVirusesDF;
//    private InjectionDF injectionDF;

    private RockPop rockPop;
    private Disposable popDisposable;
    private EditText oldEditText;
    private boolean isNewPorject;

//    private LiquidControlDF liquidControlDF;

    private Disposable fluidIntakDisposable;
    private Disposable dischargeDisposable;
    private Disposable collectDisposable;
    private Disposable changeLiquidDisposable;
    private Disposable cleanPipeDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_experiment);
        initActionBar();
        presenter = new ExperimentPresenter(this);

//        tv_referenceWeight.setText(String.valueOf(ParamsPreferences.getInstance().getReferenceWeight()));

        wv_tank.setMode(WaveView.MODE_DRAWABLE);
//        wv_tank.setDimension(WaveView.Dimension_1);
        wv_tank.setSurface(WaveView.Surface_calm);
        wv_tank.setSpeed(WaveView.SPEED_SLOW);
        wv_tank.setMax(tankMax);
        setTankProgress(300);

        gifD_FluidIntake = (GifDrawable) gifPumpFluidIntake.getDrawable();
        gifD_Waste = (GifDrawable) gifPumpWaste.getDrawable();
        gifD_Circulating = (GifDrawable) gifPumpCirculating.getDrawable();
        gifD_Reclaim = (GifDrawable) gifPumpReclaim.getDrawable();
        gifDIncubator = (GifDrawable) gif_Incubator.getDrawable();
        gifDCultureTank = (GifDrawable) gif_cultureTank.getDrawable();
        gifDMagneticStirrer = (GifDrawable) gif_magnetic_stirrer.getDrawable();

        gifD_FluidIntake.stop();
        gifD_Waste.stop();
        gifD_Circulating.stop();
        gifD_Reclaim.stop();
        gifDIncubator.stop();
        gifDCultureTank.stop();
        gifDMagneticStirrer.stop();

        fragmentManager = getSupportFragmentManager();

        fragmentManager.beginTransaction().add(R.id.frag_console, new ConsoleFrag(), null).commit();

        presenter.moveToCorrectStage();
        presenter.scheduleExperimentStage();
        initOperateByProgress();

        Switch fullScreen = findViewById(R.id.switch_full_screen);
        fullScreen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Intent intent = new Intent();
                    intent.setAction("com.norco.removebar");
                    ExperimentActivity.this.sendBroadcast(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setAction("com.norco.addbar");
                    ExperimentActivity.this.sendBroadcast(intent);
                }
            }
        });

        //设置环境参数
        presenter.setEnvironment();
        //读环境参数
        startReadEnvironmentSchedule();
        //打开风扇，培养结束时关闭
        presenter.openIncubatorTask();
        if (getIntent() != null) {
            isNewPorject = getIntent().getBooleanExtra("isNewPorject", true);
        }

        if (isNewPorject) {//开始新项目时，先清洗管路，再注入初始培养液，注入完毕再启动循环泵，磁力搅拌器
//            promoteCleanPipes();
        } else {//不是新项目，恢复项目
//            presenter.recoverAD();//恢复下位机ad值
//            initStirrerCirclingPumpAtStart();//恢复磁力搅拌器，循环泵
        }
//        presenter.scheduleChangeAir(ParamsPreferences.getInstance().getChangeAirFrequency());
        presenter.scheduleLiquidPlan();
        if (CartApplication.getInstance().isProjectStarted()) {
            requestEnvironmentParamSchedule();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.menu_experiment, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //罐子的总容量
    private int tankMax=800;
    private void setTankProgress(int progress){
        //因为这个控件达到最大值时无法回撤，所以出此下策
        progress=progress>=tankMax?799:progress;
        wv_tank.setProgress(progress);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_param_setting:
                onSetting();
                break;
            case R.id.nav_log:
                onLog();
                break;
            case R.id.nav_material:
                onRawMaterial();
                break;
            case R.id.nav_door:
                operateDoor();
                break;
            case R.id.nav_table:
                operateShakeDoor();
                break;
            case R.id.nav_fullScreen:
                fullScreenToggle();
                break;
//            case R.id.nav_shutdown:
//                DialogFragmentHelper.showConfirmDialog(this, "关闭下位机", "确认关闭下位机吗？", new IDialogResultListener<Integer>() {
//                    @Override
//                    public void onDataResult(Integer result) {
//                        if (result == DialogInterface.BUTTON_POSITIVE) {
//                            presenter.shutDown();
//                        }
//                    }
//                }, true);
//                break;
//            case R.id.nav_salineValve:
//                DialogFragmentHelper.showTwoOperateDialog(this, getString(R.string.salineValve), "", R.string.open, R.string.close, new IDialogResultListener<Integer>() {
//                    @Override
//                    public void onDataResult(Integer result) {
//                        if (result == DialogInterface.BUTTON_POSITIVE) {
//                            presenter.openSalineValve();
//                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
//                            presenter.closeSalineValve();
//                        }
//                    }
//                }, true);
//                break;
//            case R.id.nav_mediumValve:
//                DialogFragmentHelper.showTwoOperateDialog(this, getString(R.string.mediumValve), "", R.string.open, R.string.close, new IDialogResultListener<Integer>() {
//                    @Override
//                    public void onDataResult(Integer result) {
//                        if (result == DialogInterface.BUTTON_POSITIVE) {
//                            presenter.openMediumValve();
//                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
//                            presenter.closeMediumValve();
//                        }
//                    }
//                }, true);
//                break;

            case R.id.nav_airChange:
                operateChangeAir();
                break;

            default:
                break;
        }
        return true;
    }

    @Override
    public void runOnUi(Runnable runnable) {
        runOnUiThread(runnable);
    }

    private void promoteCleanPipes() {
        DialogFragmentHelper.showConfirmDialog(this, "", "是否清洗管路？", new IDialogResultListener<Integer>() {
            @Override
            public void onDataResult(Integer result) {
                if (result == DialogInterface.BUTTON_POSITIVE) {
                    cleanPipes();
                } else {
                    promoteInitCultureLiquid();
                }
            }
        }, false);
    }

    private void promoteInitCultureLiquid() {
        DialogFragmentHelper.showConfirmDialog(this, "", "是否注入初始培养液？", new IDialogResultListener<Integer>() {
            @Override
            public void onDataResult(Integer result) {
                if (result == DialogInterface.BUTTON_POSITIVE) {
                    presenter.initCultureLiquid(ParamConsts.initCultureLiquid);
                } else {

                }
            }
        }, false);
    }

    private void initCultureLiquid() {
        DialogFragmentHelper.showInputDialog(this, getString(R.string.initMedium), "加注体积", getString(R.string.ml), null, InputType.TYPE_CLASS_NUMBER, "100", 500, R.string.positive, R.string.negative, new IDialogResultListener<Object[]>() {
            @Override
            public void onDataResult(Object[] result) {
                int res = (int) result[0];
                if (res == DialogInterface.BUTTON_POSITIVE) {
                    String amountStr = (String) result[1];
                    if (!TextUtils.isEmpty(amountStr)) {
                        int amount = Integer.parseInt(amountStr);
                        presenter.initCultureLiquid(amount);
                        inputLiquidLoading.setVisibility(View.VISIBLE);
                        presenter.requestOperationLog(getString(R.string.initMedium), null);
                        setCornerIndex(btn_input_liquid, 1);
                        showCornerIndex(btn_input_liquid, getString(R.string.initMedium), (Integer) btn_input_liquid.getTag());
                    } else {
                        showDialogMessage("体积不能为空");
                    }

                }
            }
        }, this, false);
    }

    private void cleanPipes() {
        DialogFragmentHelper.showCleanPipesDialog(this, presenter.getCleanPipeTask(), new IDialogResultListener<Object[]>() {
            @Override
            public void onDataResult(Object[] result) {
                int res = (int) result[0];
                if (res == DialogInterface.BUTTON_POSITIVE) {
//                    ForceTestDF forceTestDF = new ForceTestDF();
//                    forceTestDF.show(fragmentManager, null);

                    String amountStr = (String) result[1];
                    String fluidSpeedStr = (String) result[2];
                    String loopTimeStr = (String) result[3];
                    String circlingSpeedStr = (String) result[4];
                    String wasteSpeedStr = (String) result[5];
                    String cleanNumbersStr = (String) result[6];

                    if (TextUtils.isEmpty(amountStr)) {
                        showDialogMessage("进液体积不能为空");
                    } else if (TextUtils.isEmpty(fluidSpeedStr)) {
                        showDialogMessage("进液泵速度不能为空");
                    } else if (TextUtils.isEmpty(loopTimeStr)) {
                        showDialogMessage("循环时间不能为空");
                    } else if (TextUtils.isEmpty(circlingSpeedStr)) {
                        showDialogMessage("循环泵速度不能为空");
                    } else if (TextUtils.isEmpty(wasteSpeedStr)) {
                        showDialogMessage("废液泵速度不能为空");
                    } else if (TextUtils.isEmpty(cleanNumbersStr)) {
                        showDialogMessage("清洗次数不能为空");
                    }

                    int amount = Integer.parseInt(amountStr);
                    int fluidSpeed = Integer.parseInt(fluidSpeedStr);
                    int loopTime = Integer.parseInt(loopTimeStr);
                    int circlingSpeed = Integer.parseInt(circlingSpeedStr);
                    int wasteSpeed = Integer.parseInt(wasteSpeedStr);
                    int cleanNumbers = Integer.parseInt(cleanNumbersStr);
                    presenter.cleanPipes("清洗管路", amount, amount, cleanNumbers, loopTime, fluidSpeed, circlingSpeed, wasteSpeed);
                    cleanPipeLoading.setVisibility(View.VISIBLE);
                    setCornerIndex(btn_cleanPipe, 1);
                    showCornerIndex(btn_cleanPipe, getString(R.string.cleanPipes), (Integer) btn_cleanPipe.getTag());
                } else if (res == DialogInterface.BUTTON_NEGATIVE) {

                }
            }
        });
    }

    private void clearAllCorner() {
        if (btn_materialConfirm.getTag() != null) {
            btn_materialConfirm.setTag(null);
            showCornerIndex(btn_materialConfirm, getString(R.string.getMaterial), 0);
        }
        if (btn_cleanPipe.getTag() != null) {
            btn_cleanPipe.setTag(null);
            showCornerIndex(btn_cleanPipe, getString(R.string.cleanPipes), 0);
        }
        if (btn_input_liquid.getTag() != null) {
            btn_input_liquid.setTag(null);
            showCornerIndex(btn_input_liquid, getString(R.string.initMedium), 0);
        }
        if (btnSample.getTag() != null) {
            btnSample.setTag(null);
            showCornerIndex(btnSample, getString(R.string.sampling), 0);
        }
        if (btn_add_cell.getTag() != null) {
            btn_add_cell.setTag(null);
            showCornerIndex(btn_add_cell, getString(R.string.addCell), 0);
        }
        if (btn_add_viruses.getTag() != null) {
            btn_add_viruses.setTag(null);
            showCornerIndex(btn_add_viruses, getString(R.string.addViruses), 0);
        }
        if (btn_fluidIntake.getTag() != null) {
            btn_fluidIntake.setTag(null);
            showCornerIndex(btn_fluidIntake, getString(R.string.fluidIntake), 0);
        }
        if (btn_discharge.getTag() != null) {
            btn_discharge.setTag(null);
            showCornerIndex(btn_discharge, getString(R.string.discharge), 0);
        }
        if (btn_collect.getTag() != null) {
            btn_collect.setTag(null);
            showCornerIndex(btn_collect, getString(R.string.collect), 0);
        }
        if (btn_changeLiquid.getTag() != null) {
            btn_changeLiquid.setTag(null);
            showCornerIndex(btn_changeLiquid, getString(R.string.changeLiquid), 0);
        }
        if (btn_ConcentrationReplacement.getTag() != null) {
            btn_ConcentrationReplacement.setTag(null);
            showCornerIndex(btn_ConcentrationReplacement, getString(R.string.concentrationReplace), 0);
        }
        if (addCryoprotectant.getTag() != null) {
            addCryoprotectant.setTag(null);
            showCornerIndex(addCryoprotectant, getString(R.string.addCryoprotectant), 0);
        }
        if (btn_material_kill.getTag() != null) {
            btn_material_kill.setTag(null);
            showCornerIndex(btn_material_kill, getString(R.string.material_kill), 0);
        }
        if (cleanConfirm.getTag() != null) {
            cleanConfirm.setTag(null);
            showCornerIndex(cleanConfirm, getString(R.string.cleanConfirm), 0);
        }
        if (UV_disinfection.getTag() != null) {
            UV_disinfection.setTag(null);
            showCornerIndex(UV_disinfection, getString(R.string.UV_disinfection), 0);
        }
    }

    //根据实验阶段显示相应的操作在界面底部
    private void initOperateByProgress() {
        clearAllCorner();
        changeLiquidTurn = 1;
        String stage = ExperimentStageManager.getInstance().getCurrentStage().getStage();
        switch (stage) {
            case "制备准备":
                rlMaterialConfirm.setVisibility(View.VISIBLE);
                rlDefaultParams.setVisibility(View.VISIBLE);
                rlCleanPipe.setVisibility(View.VISIBLE);
                rlInputLiquid.setVisibility(View.VISIBLE);
                iv_next.setVisibility(View.VISIBLE);
                rlSample.setVisibility(View.GONE);
                rlFluidIntake.setVisibility(View.GONE);
                split_fluidIntake.setVisibility(View.GONE);
                rlDischarge.setVisibility(View.GONE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.GONE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.GONE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);
                break;
            case "激活":
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.GONE);
                rlFluidIntake.setVisibility(View.VISIBLE);
                split_fluidIntake.setVisibility(View.GONE);
                rlDischarge.setVisibility(View.GONE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.GONE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.VISIBLE);
                rlAddViruses.setVisibility(View.GONE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);
                break;
            case "观察/感染":
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.VISIBLE);
                rlFluidIntake.setVisibility(View.VISIBLE);
                split_fluidIntake.setVisibility(View.VISIBLE);
                rlDischarge.setVisibility(View.VISIBLE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.VISIBLE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.VISIBLE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);

                break;
            case "细胞前富集":
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.VISIBLE);
                rlFluidIntake.setVisibility(View.VISIBLE);
                split_fluidIntake.setVisibility(View.VISIBLE);
                rlDischarge.setVisibility(View.VISIBLE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.VISIBLE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.VISIBLE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);
                break;
            case "细胞后富集":
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.VISIBLE);
                rlFluidIntake.setVisibility(View.VISIBLE);
                split_fluidIntake.setVisibility(View.VISIBLE);
                rlDischarge.setVisibility(View.VISIBLE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.VISIBLE);
                split_changeLiquid.setVisibility(View.VISIBLE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.GONE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.VISIBLE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);
                break;
            case "制备完成":
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.GONE);
                rlFluidIntake.setVisibility(View.GONE);
                split_fluidIntake.setVisibility(View.GONE);
                rlDischarge.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.GONE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                if (ProjectManager.getInstance().isFinishCollect()) {
                    rlConcentrationReplacement.setVisibility(View.GONE);
                    rlAddCryoprotectant.setVisibility(View.GONE);
                    rlCollect.setVisibility(View.GONE);
                    iv_finish_collect.setVisibility(View.GONE);
                    rlCleanConfirm.setVisibility(View.VISIBLE);
                    rlUVDisinfection.setVisibility(View.VISIBLE);
                    rlMaterialKill.setVisibility(View.VISIBLE);
                } else {
                    rlConcentrationReplacement.setVisibility(View.VISIBLE);
                    rlAddCryoprotectant.setVisibility(View.VISIBLE);
                    rlCollect.setVisibility(View.VISIBLE);
                    iv_finish_collect.setVisibility(View.VISIBLE);
                    rlCleanConfirm.setVisibility(View.GONE);
                    rlUVDisinfection.setVisibility(View.GONE);
                    rlMaterialKill.setVisibility(View.GONE);
                }
                break;
            default:
                rlMaterialConfirm.setVisibility(View.GONE);
                rlDefaultParams.setVisibility(View.GONE);
                rlCleanPipe.setVisibility(View.GONE);
                rlInputLiquid.setVisibility(View.GONE);
                iv_next.setVisibility(View.GONE);
                rlSample.setVisibility(View.GONE);
                rlFluidIntake.setVisibility(View.GONE);
                split_fluidIntake.setVisibility(View.GONE);
                rlDischarge.setVisibility(View.GONE);
                rlCollect.setVisibility(View.GONE);
                rlChangeLiquid.setVisibility(View.GONE);
                split_changeLiquid.setVisibility(View.GONE);
                rlAddCell.setVisibility(View.GONE);
                rlAddViruses.setVisibility(View.GONE);
                rlAddCryoprotectant.setVisibility(View.GONE);
                rlCleanConfirm.setVisibility(View.GONE);
                rlUVDisinfection.setVisibility(View.GONE);
                iv_finish_culture.setVisibility(View.GONE);
                rlConcentrationReplacement.setVisibility(View.GONE);
                rlMaterialKill.setVisibility(View.GONE);
                iv_finish_collect.setVisibility(View.GONE);
                break;
        }
    }

    private void initStirrerCirclingPumpAtStart() {
        //启动磁力搅拌器
        DeviceRecord stirrerRecord = new DeviceRecord();
        stirrerRecord.setName(getString(R.string.magnetic_stirrer) + "(开)");
        stirrerRecord.setData(ParamsPreferences.getInstance().getStirrerSpeed() + "r/min");
        stirrerRecord.setDateTime(new Date());
        stirrerRecord.setOperator("系统");
        stirrerRecord.setDevice(getString(R.string.magnetic_stirrer));
        presenter.openStirrerTask(ParamsPreferences.getInstance().getStirrerSpeed(), stirrerRecord);

        //启动循环泵
        DeviceRecord deviceRecord = new DeviceRecord();
        deviceRecord.setName(getString(R.string.peristaltic_pump_circulating) + "(开)");
        deviceRecord.setData(ParamsPreferences.getInstance().getCirculatingPumpSpeed() + "r/min");
        deviceRecord.setDirection(PeristalticPumpBO.getDirectionStr(ParamsPreferences.getInstance().getCirculatingPumpDirection()));
        deviceRecord.setDateTime(new Date());
        deviceRecord.setOperator(CartApplication.getInstance().getOperator());
        deviceRecord.setDevice(getString(R.string.peristaltic_pump_circulating));
        presenter.saveDeviceRecord(deviceRecord);
        presenter.openPumpTask(PeristalticPumpBO.PeristalticPump_circulating, ParamsPreferences.getInstance().getCirculatingPumpSpeed(), ParamsPreferences.getInstance().getCirculatingPumpDirection(), null);
    }

    private void initActionBar() {
        toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            Drawable drawable = getResources().getDrawable(R.mipmap.setting);
            toolbar.setOverflowIcon(drawable);
//            home = findViewById(R.id.home);
            tv_title = findViewById(R.id.title);
//            setting = findViewById(R.id.setting);
//            log = findViewById(R.id.log);
//            View console = findViewById(R.id.console);
//            console.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onConsole();
//                }
//            });
//            View door = findViewById(R.id.door);
//            door.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    operateDoor();
//                }
//            });
//            home.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onHome();
//                }
//            });
//            setting.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onSetting();
//                }
//            });
//            log.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onLog();
//                }
//            });
//            View control = findViewById(R.id.control);
//            control.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onControl();
//                }
//            });

//            final Spinner spinner_set = findViewById(R.id.spinner_set);
//            spinner_set.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                @Override
//                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                    if (position == 1) {//参数
//                        onSetting();
//                    } else if (position == 2) {//日志
//                        onLog();
//                    } else if (position == 3) {//换液计划
//                        onChangeLiquidPlan();
//                    } else if (position == 4) {//原材料
//                        onRawMaterial();
//                    }
//                    spinner_set.setSelection(0);
//                }
//
//                @Override
//                public void onNothingSelected(AdapterView<?> parent) {
//
//                }
//            });

            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayShowTitleEnabled(false);
            }
        }
    }

    private void startReadEnvironmentSchedule() {
        presenter.scheduleReadCO2();
        presenter.scheduleReadO2();
        presenter.scheduleReadTemperature();
//        presenter.scheduleWeight();
    }

    //定时发送环境信息
    private void requestEnvironmentParamSchedule() {
        presenter.scheduleRequestEnvironmentParams();
    }

    private void onLog() {
        LogDF logDF = new LogDF();
        logDF.show(fragmentManager, null);
    }

    private void onControl() {
        InternalControlDF internalControlDF = new InternalControlDF();
        internalControlDF.show(fragmentManager, null);
    }

    private void onHome() {
        ProgressOverViewDF progressOverViewDF = new ProgressOverViewDF();
        progressOverViewDF.setStageNameChange(new ProgressOverViewDF.OnStageNameChange() {
            @Override
            public void onStageNameChange(String newName) {
                setTitle(ExperimentStageManager.getInstance().getCurrentStage().getDay(), newName);
            }
        });
        progressOverViewDF.show(fragmentManager, null);
    }

    private void onConsole() {
        if (frameLayout.getVisibility() == View.VISIBLE) {
            frameLayout.setVisibility(View.GONE);
        } else if (frameLayout.getVisibility() == View.GONE) {
            frameLayout.setVisibility(View.VISIBLE);
        }
    }

    private void onSetting() {
        SetParamsDF setParamsDF = new SetParamsDF();
        setParamsDF.show(fragmentManager, null);
    }

    @Override
    public void setPorgress1(int progress) {
        progressBar1.setProgress(progress);
//        if(progress>0) {
//            progressBar1.setVisibility(View.VISIBLE);
//        }else {
//            progressBar1.setVisibility(View.GONE);
//        }
    }

    @Override
    public void setPorgress1Max(int max) {
        progressBar1.setMax(max);
    }

    @Override
    public int getProgress1() {
        return progressBar1.getProgress();
    }

    @Override
    public int getProgress1Max() {
        return progressBar1.getMax();
    }

    @Override
    public void setPorgress2(int progress) {
        progressBar2.setProgress(progress);
    }

    @Override
    public void setPorgress2Max(int max) {
        progressBar2.setMax(max);
    }

    @Override
    public int getProgress2() {
        return progressBar2.getProgress();
    }

    @Override
    public int getProgress2Max() {
        return progressBar2.getMax();
    }

    @Override
    public void setPorgress3(int progress) {
        progressBar3.setProgress(progress);
//        if (progress != progressBar3.getMax()) {
//            progressBar3.setVisibility(View.VISIBLE);
//        } else {
//            progressBar3.setVisibility(View.GONE);
//        }
    }

    @Override
    public void setPorgress3Max(int max) {
        progressBar3.setMax(max);
    }

    @Override
    public int getProgress3() {
        return progressBar3.getProgress();
    }

    @Override
    public int getProgress3Max() {
        return progressBar3.getMax();
    }

    @Override
    public void setPorgress4(int progress) {
        progressBar4.setProgress(progress);
    }

    @Override
    public void setPorgress4Max(int max) {
        progressBar4.setMax(max);
    }

    @Override
    public int getProgress4() {
        return progressBar4.getProgress();
    }

    @Override
    public int getProgress4Max() {
        return progressBar4.getMax();
    }

    @Override
    public void setPorgress4Visibility(int visibility) {
        progressBar4.setVisibility(visibility);
    }

    @Override
    public void setPorgress1Visibility(int visibility) {
        progressBar1.setVisibility(visibility);
        tv_fluidIntake_countdown.setVisibility(visibility);
    }

    @Override
    public void setPorgress2Visibility(int visibility) {
        progressBar2.setVisibility(visibility);
        tv_discharge_countdown.setVisibility(visibility);
    }

    @Override
    public void setPorgress3Visibility(int visibility) {
        progressBar3.setVisibility(visibility);
        tv_collect_countdown.setVisibility(visibility);
    }

    @Override
    public void clearAllProgress() {
        progressBar1.setVisibility(View.GONE);
        progressBar2.setVisibility(View.GONE);
        progressBar3.setVisibility(View.GONE);
        progressBar4.setVisibility(View.GONE);
        stopFluidInputProgressBar();
        stoptDischargeProgressBar();
        stopChangeLiquidProgressBar();
        stopCleanPipeProgressBar();
        tv_fluidIntake_countdown.setVisibility(View.GONE);
        tv_discharge_countdown.setVisibility(View.GONE);
        tv_collect_countdown.setVisibility(View.GONE);
    }

    @Override
    public void setFluidIntakeCountDown(int count) {
        tv_fluidIntake_countdown.setText(String.valueOf(count));
        if (count != 0) {
            tv_fluidIntake_countdown.setVisibility(View.VISIBLE);
        } else {
            tv_fluidIntake_countdown.setVisibility(View.GONE);
        }
    }

    @Override
    public void setDischargeCountDown(int count) {
        tv_discharge_countdown.setText(String.valueOf(count));
        if (count != 0) {
            tv_discharge_countdown.setVisibility(View.VISIBLE);
        } else {
            tv_discharge_countdown.setVisibility(View.GONE);
        }
    }

    @Override
    public void setCollectCountDown(int count) {
        tv_collect_countdown.setText(String.valueOf(count));
        if (count != 0) {
            tv_collect_countdown.setVisibility(View.VISIBLE);
        } else {
            tv_collect_countdown.setVisibility(View.GONE);
        }
    }

    @Override
    public void setChangeCountDown(int count) {
        tv_changeLiquid_countdown.setText(String.valueOf(count));
        if (count != 0) {
            tv_changeLiquid_countdown.setVisibility(View.VISIBLE);
        } else {
            tv_changeLiquid_countdown.setVisibility(View.GONE);
        }
    }

    @Override
    public void moveToStage(final ExperimentStage experimentStage) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setTitle(experimentStage.getDay(), experimentStage.getStage());
                initOperateByProgress();
            }
        });
    }

    @OnClick({R.id.rl_scale, R.id.gif_pump_fluidIntake, R.id.gif_pump_waste, R.id.gif_pump_circulating, R.id.gif_pump_reclaim, R.id.fl_UltravioletLight, R.id.gif_magnetic_stirrer, R.id.gif_Incubator, R.id.gif_cultureTank, R.id.ll_CO2, R.id.ll_O2, R.id.ll_temperature})
    public void onDeviceClick(View device) {
        switch (device.getId()) {
            case R.id.rl_scale:
                DialogFragmentHelper.showTwoOperateDialog(this, getString(R.string.electronicScale), null, R.string.weight, R.string.peel, new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.weight();
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.peel(new byte[]{0, 0, 0, 0});
                        }
                    }
                }, true);
                break;
            case R.id.gif_pump_fluidIntake:
//                byte[] bytes=new byte[]{(byte) 0xBA,0x00,0x0F,0x56,0x01, (byte) 0xE0, (byte) 0xAA, (byte) 0xC8, (byte) 0xDE,0x63,0x52, (byte) 0xFF,0x20,0x0A,0x02, (byte) 0xAA,0x00,0x00, (byte) 0xED};
//                TestDecoder testDecoder=new TestDecoder();
//                try {
//                    Protocol protocol=testDecoder.decode(bytes);
//                    protocol.parse2BO();
//                } catch (UnpackException e) {
//                    e.printStackTrace();
//                } catch (ProtocolException e) {
//                    e.printStackTrace();
//                }

//                setFluidInputProgressBar(26);
//                startFluidInputProgressBar();
                int speed_fluidIntake = ParamsPreferences.getInstance().getFluidIntakePumpSpeed();
                byte direction_fluidIntake = ParamsPreferences.getInstance().getFluidIntakePumpDirection();
                operatePump(PeristalticPumpBO.PeristalticPump_fluidIntake, speed_fluidIntake, direction_fluidIntake);
                break;
            case R.id.gif_pump_waste:
//                adjustFluidInputProgressBar(26);
                int speed_waste = ParamsPreferences.getInstance().getWastePumpSpeed();
                byte direction_waste = ParamsPreferences.getInstance().getWastePumpDirection();
                operatePump(PeristalticPumpBO.PeristalticPump_waste, speed_waste, direction_waste);
                break;
            case R.id.gif_pump_circulating:
                int speed_circulating = ParamsPreferences.getInstance().getCirculatingPumpSpeed();
                byte direction_circulating = ParamsPreferences.getInstance().getCirculatingPumpDirection();
                operatePump(PeristalticPumpBO.PeristalticPump_circulating, speed_circulating, direction_circulating);
                break;
            case R.id.gif_pump_reclaim:
                int speed_reclaim = ParamsPreferences.getInstance().getReclaimPumpSpeed();
                byte direction_reclaim = ParamsPreferences.getInstance().getReclaimPumpDirection();
                operatePump(PeristalticPumpBO.PeristalticPump_reclaim, speed_reclaim, direction_reclaim);
                break;
            case R.id.fl_UltravioletLight:
                DialogFragmentHelper.showTwoOperateDialog(this, getString(R.string.UltravioletLight), null, R.string.lightOn, R.string.lightOff, new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.openUltravioletLightTask();
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.closeUltravioletLightTask();
                        }
                    }
                }, true);
                break;
            case R.id.gif_magnetic_stirrer:
                String speed_stirrer = String.valueOf(ParamsPreferences.getInstance().getStirrerSpeed());
                DialogFragmentHelper.showStirrerDialog(this, speed_stirrer, new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int witch = (int) result[0];
                        if (witch == DialogInterface.BUTTON_POSITIVE) {
                            String speedStr = (String) result[1];
                            if (TextUtils.isEmpty(speedStr)) {
                                onError("速度不能为空");
                                return;
                            }
                            int speed = Integer.parseInt(speedStr);
                            if (speed > ParamConsts.maxStirrerSpeed) {
                                onError("磁力搅拌器转速不能超过" + ParamConsts.maxStirrerSpeed);
                                return;
                            }
                            DeviceRecord dr_stirrer = new DeviceRecord();
                            dr_stirrer.setName(getString(R.string.magnetic_stirrer) + "(开)");
                            dr_stirrer.setData(speed + "r/min");
                            dr_stirrer.setOperator(CartApplication.getInstance().getOperator());
                            dr_stirrer.setDateTime(new Date());
                            dr_stirrer.setDevice(getString(R.string.magnetic_stirrer));
                            presenter.openStirrerTask(speed, dr_stirrer);
                            ParamsPreferences.getInstance().setStirrerSpeedCommit(speed);
                        } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                            DeviceRecord dr_stirrer = new DeviceRecord();
                            dr_stirrer.setName(getString(R.string.magnetic_stirrer) + "(关)");
                            dr_stirrer.setOperator(CartApplication.getInstance().getOperator());
                            dr_stirrer.setDateTime(new Date());
                            dr_stirrer.setDevice(getString(R.string.magnetic_stirrer));
                            presenter.closeStirrerTask(dr_stirrer);
                        }
                    }
                }, this);
                break;
            case R.id.gif_Incubator:
                DialogFragmentHelper.showTwoOperateDialog(this, getString(R.string.incubator), null, R.string.run, R.string.stop, new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.openIncubatorTask();
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.closeIncubatorTask();
                        }
                    }
                }, true);
                break;
            case R.id.gif_cultureTank:
                DialogFragmentHelper.showCultureTankDialog(this, String.valueOf(ParamsPreferences.getInstance().getCultureTankSpeed()), new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int witch = (int) result[0];
                        if (witch == DialogInterface.BUTTON_POSITIVE) {
                            String speedStr = (String) result[1];
                            if (TextUtils.isEmpty(speedStr)) {
                                onError("速度不能为空");
                                return;
                            }
                            int speed = Integer.parseInt(speedStr);
                            if (speed > ParamConsts.maxCultureSpeed) {
                                onError("培养罐换气泵转速不能超过" + ParamConsts.maxCultureSpeed);
                                return;
                            }

                            DeviceRecord dr_culture_tank = new DeviceRecord();
                            dr_culture_tank.setName(getString(R.string.cultureTankElectric) + "(开)");
                            dr_culture_tank.setData(speed + "r/min");
                            dr_culture_tank.setOperator(CartApplication.getInstance().getOperator());
                            dr_culture_tank.setDateTime(new Date());
                            dr_culture_tank.setDevice(getString(R.string.cultureTankElectric));

                            presenter.openCultureTankTask(speed, dr_culture_tank);
                            ParamsPreferences.getInstance().setCultureTankSpeed(speed);
                        } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                            DeviceRecord dr_culture_tank = new DeviceRecord();
                            dr_culture_tank.setName(getString(R.string.cultureTankElectric) + "(关)");
                            dr_culture_tank.setOperator(CartApplication.getInstance().getOperator());
                            dr_culture_tank.setDateTime(new Date());
                            dr_culture_tank.setDevice(getString(R.string.cultureTankElectric));
                            presenter.closeCultureTankTask(dr_culture_tank);
                        }
                    }
                }, this);
                break;
            case R.id.ll_CO2:
                Double settedCO2 = CO2Controller.getInstance().getSettedValue();
                DialogFragmentHelper.showEnvironmentDialog(this, getString(R.string.CO2), getString(R.string.percent), String.format("%.01f", settedCO2 == null ? 0 : settedCO2), ParamConsts.maxCO2, new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int witch = (int) result[0];
                        if (witch == DialogInterface.BUTTON_POSITIVE) {
                            String co2Str = (String) result[1];
                            if (TextUtils.isEmpty(co2Str)) {
                                onError("CO2不能为空");
                            } else {
                                try {
                                    double co2 = Double.parseDouble(co2Str);
                                    if (co2 > ParamConsts.maxCO2) {
                                        onError("CO2不能超过" + ParamConsts.maxCO2);
                                        return;
                                    } else if (co2 < ParamConsts.minCO2) {
                                        onError("CO2不能低于" + ParamConsts.minCO2);
                                        return;
                                    }
                                    presenter.setCO2(co2);
                                } catch (NumberFormatException e) {
                                    onError("输入有误");
                                }
                            }
                        } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.ReadCO2();
                        }
                    }
                }, this);
                break;
            case R.id.ll_O2:
                Double settedO2 = O2Controller.getInstance().getSettedValue();
                DialogFragmentHelper.showEnvironmentDialog(this, getString(R.string.O2), getString(R.string.percent), String.format("%.01f", settedO2 == null ? 0 : settedO2), ParamConsts.maxO2, new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int witch = (int) result[0];
                        if (witch == DialogInterface.BUTTON_POSITIVE) {
                            String o2Str = (String) result[1];
                            if (TextUtils.isEmpty(o2Str)) {
                                onError("O2不能为空");
                            } else {
                                try {
                                    double o2 = Double.parseDouble(o2Str);
                                    if (o2 > ParamConsts.maxO2) {
                                        onError("O2不能超过" + ParamConsts.maxO2);
                                        return;
                                    } else if (o2 < ParamConsts.minO2) {
                                        onError("O2不能低于" + ParamConsts.minO2);
                                        return;
                                    }
                                    presenter.setO2(o2);
                                } catch (NumberFormatException e) {
                                    onError("输入有误");
                                }
                            }
                        } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.ReadO2();
                        }
                    }
                }, this);
                break;
            case R.id.ll_temperature:
                Double settedTemperature = TemperatureController.getInstance().getSettedValue();
                DialogFragmentHelper.showEnvironmentDialog(this, getString(R.string.temperature), getString(R.string.centigrade), String.format("%.01f", settedTemperature == null ? 0 : settedTemperature), ParamConsts.maxTemperature, new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int witch = (int) result[0];
                        if (witch == DialogInterface.BUTTON_POSITIVE) {
                            String temperatureStr = (String) result[1];
                            if (TextUtils.isEmpty(temperatureStr)) {
                                onError("温度不能为空");
                            } else {
                                try {
                                    double temperature = Double.parseDouble(temperatureStr);
                                    if (temperature > ParamConsts.maxTemperature) {
                                        onError("温度不能超过" + ParamConsts.maxTemperature);
                                        return;
                                    } else if (temperature < ParamConsts.minTemperature) {
                                        onError("温度不能低于" + ParamConsts.minTemperature);
                                        return;
                                    }
                                    presenter.setTemperature(temperature);
                                } catch (NumberFormatException e) {
                                    onError("输入有误");
                                }
                            }
                        } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.ReadTemperature();
                        }
                    }
                }, this);
                break;
            default:
                break;
        }
    }

    private void operatePump(final byte ModularNO, int speed, byte direction) {
        DialogFragmentHelper.showPumpOperateDialog(this, getString(PeristalticPumpBO.getModularNOStrByCode(ModularNO)), speed, direction, new IDialogResultListener<Object[]>() {
            @Override
            public void onDataResult(Object[] result) {
                int witch = (int) result[0];
                if (witch == DialogInterface.BUTTON_POSITIVE) {
                    String speedStr = (String) result[1];
                    if (TextUtils.isEmpty(speedStr)) {
                        onError("速度不能为空");
                        return;
                    }
                    int speed = Integer.parseInt(speedStr);
                    if (speed > ParamConsts.maxPumpSpeed) {
                        onError("速度不能超过" + ParamConsts.maxPumpSpeed);
                        return;
                    }
                    byte direction = (byte) result[2];
                    presenter.setIsTesting(true);
                    DeviceRecord deviceRecord = new DeviceRecord();
                    deviceRecord.setName(getString(PeristalticPumpBO.getModularNOStrByCode(ModularNO)) + "(" + "开" + ")");
                    deviceRecord.setData(speedStr + "r/min ");
                    deviceRecord.setDirection(PeristalticPumpBO.getDirectionStr(direction));
                    deviceRecord.setDateTime(new Date());
                    deviceRecord.setOperator(CartApplication.getInstance().getOperator());
                    deviceRecord.setDevice(getString(PeristalticPumpBO.getModularNOStrByCode(ModularNO)));
                    presenter.saveDeviceRecord(deviceRecord);
                    presenter.openPumpTask(ModularNO, speed, direction, null);

//                    presenter.saveOperation(operation);
//                    if (ModularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
//                        ParamsPreferences.getInstance().setFluidIntakePumpCommit(speed, direction);
//                    } else if (ModularNO == PeristalticPumpBO.PeristalticPump_waste) {
//                        ParamsPreferences.getInstance().setWastePumpCommit(speed, direction);
//                    } else if (ModularNO == PeristalticPumpBO.PeristalticPump_circulating) {
//                        ParamsPreferences.getInstance().setCirculatingPumpCommit(speed, direction);
//                    } else if (ModularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
//                        ParamsPreferences.getInstance().setReclaimPumpCommit(speed, direction);
//                    }
                } else if (witch == DialogInterface.BUTTON_NEGATIVE) {
                    presenter.setIsTesting(true);
                    DeviceRecord deviceRecord = new DeviceRecord();
                    deviceRecord.setName(getString(PeristalticPumpBO.getModularNOStrByCode(ModularNO)) + "(" + "关" + ")");
                    deviceRecord.setDateTime(new Date());
                    deviceRecord.setOperator(CartApplication.getInstance().getOperator());
                    deviceRecord.setDevice(getString(PeristalticPumpBO.getModularNOStrByCode(ModularNO)));
                    presenter.saveDeviceRecord(deviceRecord);
                    presenter.closePumpTask(ModularNO, null);
                }
            }
        }, this);
    }

    @Override
    public void onWeightFailed() {
        addCryoprotectantLoading.setVisibility(View.GONE);
        concentrationReplacementLoading.setVisibility(View.GONE);
        changeLiquidLoading.setVisibility(View.GONE);
        collectLoading.setVisibility(View.GONE);
        dischargeLoading.setVisibility(View.GONE);
        fluidIntakeLoading.setVisibility(View.GONE);
        inputLiquidLoading.setVisibility(View.GONE);
        cleanPipeLoading.setVisibility(View.GONE);
        clearAllProgress();
        if (isAddCell && addCellDF != null) {
            addCellDF.startAddFailed();
        }
        if (isAddViruses && addVirusesDF != null) {
            addVirusesDF.startAddFailed();
        }
    }

    private int changeLiquidTurn = 1;
    private ChangeLiquidTXDF.onChangeLiquid onChangeLiquid = new ChangeLiquidTXDF.onChangeLiquid() {
        @Override
        public void onChangeLiquidFirstTurn(int firstTimeAmount, int secondTimeAmount, int thirdTimeAmount, Date data, String operator) {
//            changeLiquidTurn=1;
            changeLiquidOneTurn(firstTimeAmount, secondTimeAmount, thirdTimeAmount, data, operator);
        }

        @Override
        public void onChangeLiquidSecondTurn(int firstTimeAmount, int secondTimeAmount, int thirdTimeAmount, Date data, String operator) {
//            changeLiquidTurn=2;
            changeLiquidOneTurn(firstTimeAmount, secondTimeAmount, thirdTimeAmount, data, operator);
        }

        @Override
        public void onChangeLiquidThirdTurn(int firstTimeAmount, int secondTimeAmount, int thirdTimeAmount, Date data, String operator) {
//            changeLiquidTurn=3;
            changeLiquidOneTurn(firstTimeAmount, secondTimeAmount, thirdTimeAmount, data, operator);
        }

        @Override
        public void onTerminate() {
            presenter.terminateChangeLiquid();
        }
    };

    private CleanPipesDF cleanPipesDF;
    private LiquidControlDF liquidControlDF;
    private ChangeLiquidTXDF changeLiquidTXDF;
    private ConcentrationReplacementDF concentrationReplacementDF;
    @OnClick({R.id.iv_finish_collect, R.id.rl_UV_disinfection, R.id.rl_cleanConfirm, R.id.rl_addCryoprotectant, R.id.rl_ConcentrationReplacement, R.id.rl_material_kill, R.id.iv_finish_culture, R.id.rl_materialConfirm, R.id.rl_defaultParams, R.id.rl_cleanPipe, R.id.rl_input_liquid, R.id.iv_next, R.id.rl_add_cell, R.id.rl_add_viruses, R.id.rl_fluidIntake, R.id.rl_discharge, R.id.rl_sample, R.id.rl_collect, R.id.rl_changeLiquid})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_materialConfirm:
                onRawMaterial();
                break;
            case R.id.rl_defaultParams:
                onSetting();
                break;
            case R.id.rl_cleanPipe:
//                cleanPipes();
                cleanPipesDF = CleanPipesDF.newInstance(presenter.getCleanPipeTask());
                cleanPipesDF.setOnCleanPipes(new CleanPipesDF.OnCleanPipes() {
                    @Override
                    public void cleanPipes(int fluidAmount, int wasteAmount, int cleanNumbers, int loopTime, int fluidSpeed, int circlingSpeed, int wasteSpeed) {
                        presenter.cleanPipes("清洗管路", fluidAmount, wasteAmount, cleanNumbers, loopTime, fluidSpeed, circlingSpeed, wasteSpeed);
                    }

                    @Override
                    public void terminateCleanPipes() {
                        presenter.terminateCleanPipe();
                    }
                });
                cleanPipesDF.show(fragmentManager, null);
                break;
            case R.id.rl_input_liquid:
                initCultureLiquid();
                break;
            case R.id.iv_next:
                DialogFragmentHelper.showConfirmDialog(this, "", "是否确认进入到Day1界面？", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.requestOpenProject();
//                            onRequestOpenProject();
                        }
                    }
                }, true);
                break;
            case R.id.rl_sample:
                sample();
                break;
//            case R.id.btn_inject:
//                injection();
//                break;
            case R.id.rl_fluidIntake:
                operateLiquid(Operation.Operate_FluidIntake, presenter.getFluidIntakenTask());
                break;
            case R.id.rl_discharge:
                operateLiquid(Operation.Operate_Discharge, presenter.getDischargeTask());
                break;
            case R.id.rl_collect:
                operateLiquid(Operation.Operate_Collect, presenter.getCollectTask());
//                presenter.test11();
                break;
            case R.id.rl_changeLiquid:
                changeLiquidTXDF = ChangeLiquidTXDF.newInstance(presenter.getChangeLiquidTask(), changeLiquidTurn);
                changeLiquidTXDF.setOnChangeLiquid(onChangeLiquid);
                changeLiquidTXDF.show(fragmentManager, null);

//                ChangeLiquidDF changeLiquidDF = ChangeLiquidDF.newInstance(presenter.getChangeLiquidBO());
//                changeLiquidDF.show(fragmentManager, null);
//                changeLiquidDF.setOnChangeLiquid(new ChangeLiquidDF.OnChangeLiquid() {
//                    @Override
//                    public void onSaveChangeLiquid(ChangeLiquidBO changeLiquidBO) {
//                        presenter.changeLiquid(changeLiquidBO,new Date(),CartApplication.getInstance().getOperator());
//                        changeLiquidLoading.setVisibility(View.VISIBLE);
//
//                        Operation operation = new Operation();
//                        operation.setName(Operation.Operate_ChangeLiquid);
//                        operation.setDateTime(new Date());
//                        operation.setOperator(CartApplication.getInstance().getOperator());
//                        operation.setData("设定置换任务");
//                        presenter.saveOperation(operation);
//                    }
//
//                    @Override
//                    public void onEditChangeLiquid(ChangeLiquidBO changeLiquidBO) {
//                        presenter.editChangeLiquid(changeLiquidBO);
//                        Operation operation = new Operation();
//                        operation.setName(Operation.Operate_ChangeLiquid);
//                        operation.setDateTime(new Date());
//                        operation.setOperator(CartApplication.getInstance().getOperator());
//                        operation.setData("修改置换任务");
//                        presenter.saveOperation(operation);
//                    }
//                });
                break;
            case R.id.rl_add_cell:
                addCell();
//                injection();
//                operateLiquid(Operation.Operate_AddCell);
                break;
            case R.id.rl_add_viruses:
//                injection();
                addViruses();
//                operateLiquid(Operation.Operate_AddViruses, presenter.getFluidIntakenTask());
                break;
            case R.id.iv_finish_culture://制备完成
                DialogFragmentHelper.showConfirmDialog(this, "", "是否确认进入到制备完成界面？", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            ExperimentStageManager.getInstance().finishCulture();
                            moveToStage(ExperimentStageManager.getInstance().getCurrentStage());
                        }
                    }
                }, true);
                break;
            case R.id.rl_ConcentrationReplacement://浓缩置换
                concentrationReplacementDF =ConcentrationReplacementDF.newInstance(presenter.getChangeLiquidTask());
                concentrationReplacementDF.setOnConcentrationReplacement(new ConcentrationReplacementDF.OnConcentrationReplacement() {
                    @Override
                    public void concentrationReplacement(int fluidAmount, int wasteAmount, int times,Date date,String user) {
                        ChangeLiquidBO changeLiquidBO = new ChangeLiquidBO();
                        ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn = changeLiquidBO.new ChangeLiquidTurn();
                        List<ChangeLiquidAmount> changeLiquidAmountList = new ArrayList<>();
                        for (int i = 0; i < times; i++) {
                            changeLiquidAmountList.add(new ChangeLiquidAmount(wasteAmount, fluidAmount, LiquidLoopTask.Liquid_saline));
                        }
                        changeLiquidTurn.setAmountList(changeLiquidAmountList);
                        changeLiquidTurn.setIntervalTime(0);
                        List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = new ArrayList<>();
                        changeLiquidTurnList.add(changeLiquidTurn);
                        changeLiquidBO.setChangeLiquidTurnList(changeLiquidTurnList);
                        presenter.changeLiquid(changeLiquidBO, date, user);
                        concentrationReplacementLoading.setVisibility(View.VISIBLE);
                        presenter.requestOperationLog("浓缩置换", "");
                    }

                    @Override
                    public void terminateConcentrationReplacement() {
                        presenter.terminateChangeLiquid();
                    }
                });
                concentrationReplacementDF.show(fragmentManager,null);
//                DialogFragmentHelper.showConcentrationReplacementDialog(this, presenter.getChangeLiquidTask(), new IDialogResultListener<Object[]>() {
//                    @Override
//                    public void onDataResult(Object[] result) {
//                        int res = (int) result[0];
//                        if (res == DialogInterface.BUTTON_POSITIVE) {
//                            String wasteAmountStr = (String) result[1];
//                            String fluidAmountStr = (String) result[2];
//                            String timesStr = (String) result[3];
//                            Date date = (Date) result[4];
//                            String userStr = (String) result[5];
//                            if (TextUtils.isEmpty(wasteAmountStr) || wasteAmountStr.equals("0")) {
//                                showDialogMessage("排液体积不能为空");
//                                return;
//                            } else if (TextUtils.isEmpty(fluidAmountStr) || wasteAmountStr.equals("0")) {
//                                showDialogMessage("进液体积不能为空");
//                                return;
//                            } else if (TextUtils.isEmpty(timesStr)) {
//                                showDialogMessage("置换次数不能为空");
//                                return;
//                            } else if (date == null) {
//                                showDialogMessage("操作时间不能为空");
//                                return;
//                            } else if (TextUtils.isEmpty(userStr)) {
//                                showDialogMessage("操作人不能为空");
//                                return;
//                            }
//                            int times = Integer.parseInt(timesStr);
//                            if (times <= 0) {
//                                showDialogMessage("置换次数必须大于0");
//                            }
//                            int wasteAmount = Integer.parseInt(wasteAmountStr);
//                            int fluidAmount = Integer.parseInt(fluidAmountStr);
//
//                            String user = (String) result[5];
//
//                            ChangeLiquidBO changeLiquidBO = new ChangeLiquidBO();
//                            ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn = changeLiquidBO.new ChangeLiquidTurn();
//                            List<ChangeLiquidAmount> changeLiquidAmountList = new ArrayList<>();
//                            for (int i = 0; i < times; i++) {
//                                changeLiquidAmountList.add(new ChangeLiquidAmount(wasteAmount, fluidAmount, LiquidLoopTask.Liquid_saline));
//                            }
//                            changeLiquidTurn.setAmountList(changeLiquidAmountList);
//                            changeLiquidTurn.setIntervalTime(0);
//                            List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = new ArrayList<>();
//                            changeLiquidTurnList.add(changeLiquidTurn);
//                            changeLiquidBO.setChangeLiquidTurnList(changeLiquidTurnList);
//                            presenter.changeLiquid(changeLiquidBO, date, user);
//                            concentrationReplacementLoading.setVisibility(View.VISIBLE);
//                            presenter.requestOperationLog("浓缩置换", "");
//                        }
//                    }
//                });
                break;
            case R.id.rl_addCryoprotectant://添加冻存保护剂
                operateLiquid(Operation.Operate_AddCryoprotectant, presenter.getFluidIntakenTask());
                break;
            case R.id.rl_material_kill://耗材消毒
                DialogFragmentHelper.showMaterialKillDialog(this, presenter.getCleanPipeTask(), new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int res = (int) result[0];
                        if (res == DialogInterface.BUTTON_POSITIVE) {
                            String fluidAmountStr = (String) result[1];
                            String wasteAmountStr = (String) result[2];
                            String loopTimeStr = (String) result[3];
                            if (TextUtils.isEmpty(fluidAmountStr)) {
                                showDialogMessage("进液体积不能为空");
                            } else if (TextUtils.isEmpty(wasteAmountStr)) {
                                showDialogMessage("废液体积不能为空");
                            } else if (TextUtils.isEmpty(loopTimeStr)) {
                                showDialogMessage("循环时间不能为空");
                            }
                            int fluidAmpunt = Integer.parseInt(fluidAmountStr);
                            int wasteAmpunt = Integer.parseInt(wasteAmountStr);
                            int loopTimes = Integer.parseInt(loopTimeStr);
                            presenter.cleanPipes("杀菌消毒", fluidAmpunt, wasteAmpunt, 1, loopTimes, ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), ParamsPreferences.getInstance().getCirculatingPumpSpeed(), ParamsPreferences.getInstance().getWastePumpSpeed());
                        }
                    }
                });
                break;
            case R.id.rl_cleanConfirm://清洁确认
                DialogFragmentHelper.showCleanConfirm(this, new IDialogResultListener<Object[]>() {
                    @Override
                    public void onDataResult(Object[] result) {
                        int res = (int) result[0];
                        if (res == DialogInterface.BUTTON_POSITIVE) {
                            Boolean isCleanConfirmed = (Boolean) result[1];
                        }
                    }
                });
                break;
            case R.id.rl_UV_disinfection:
                DialogFragmentHelper.showConfirmDialog(this, "紫外线消毒", "将关闭所有操作，关闭舱门，确认？", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.stopAllOperate();
                            Intent intent = new Intent(ExperimentActivity.this, UltravioletSterilizationActivity.class);
                            intent.putExtra("sterilizationTime", 30 * 60);
                            intent.putExtra("afterCulture", true);
                            startActivity(intent);
                        }
                    }
                }, true);
                break;
            case R.id.iv_finish_collect:
                DialogFragmentHelper.showConfirmDialog(this, "罐装完成", "确认罐装完成？将进入设备清理流程！", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.closeIncubatorTask();
                            presenter.requestFinishReclaim();
                            onRequestFinishReclaim();
                        }
                    }
                }, true);
                break;
            default:
                break;
        }
    }

    private void addCell() {
        addCellDF = new AddCellDF();
        addCellDF.setOnAddCell(this);
        addCellDF.show(fragmentManager, null);
    }

    private void addViruses() {
        addVirusesDF = new AddVirusesDF();
        addVirusesDF.setOnAddViruses(this);
        addVirusesDF.show(fragmentManager, null);
    }

    private void changeLiquidOneTurn(int firstTimeAmount, int secondTimeAmount, int thirdTimeAmount, Date data, String operator) {
        ChangeLiquidBO changeLiquidBO = new ChangeLiquidBO();
        ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn = changeLiquidBO.new ChangeLiquidTurn();
        ChangeLiquidAmount firstAmount = new ChangeLiquidAmount(firstTimeAmount, firstTimeAmount, LiquidLoopTask.Liquid_medium);
        ChangeLiquidAmount secondAmount = new ChangeLiquidAmount(secondTimeAmount, secondTimeAmount, LiquidLoopTask.Liquid_medium);
        ChangeLiquidAmount thirdAmount = new ChangeLiquidAmount(thirdTimeAmount, thirdTimeAmount, LiquidLoopTask.Liquid_medium);
        List<ChangeLiquidAmount> changeLiquidAmountList = new ArrayList<>();
        changeLiquidAmountList.add(firstAmount);
        changeLiquidAmountList.add(secondAmount);
        changeLiquidAmountList.add(thirdAmount);
        changeLiquidTurn.setAmountList(changeLiquidAmountList);
        changeLiquidTurn.setIntervalTime(0);
        List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = new ArrayList<>();
        changeLiquidTurnList.add(changeLiquidTurn);
        changeLiquidBO.setChangeLiquidTurnList(changeLiquidTurnList);
        presenter.changeLiquid(changeLiquidBO, data, operator);
        changeLiquidLoading.setVisibility(View.VISIBLE);
        setCornerIndex(btn_changeLiquid, 1);
        showCornerIndex(btn_changeLiquid, getString(R.string.changeLiquid), (Integer) btn_changeLiquid.getTag());
    }

    private void operateLiquid(String operate, LiquidLoopTask liquidLoopTask) {
        liquidControlDF = LiquidControlDF.newInstance(operate, liquidLoopTask);
        liquidControlDF.setLiquidControl(this);
        liquidControlDF.show(fragmentManager, null);
//        if (liquidControlDF == null) {
//            liquidControlDF = LiquidControlDF.newInstance(operate);
//            liquidControlDF.setLiquidControl(this);
//        } else {
//            liquidControlDF.changeOperateBundle(operate);
//        }
//        liquidControlDF.show(fragmentManager, null);
    }

    @Override
    public void onRequestOpenProject() {
        showDialogMessage("开启项目成功");
        ExperimentStageManager.getInstance().forwardStage();
        moveToStage(ExperimentStageManager.getInstance().getCurrentStage());
        //开启项目后发送环境信息给服务器
        requestEnvironmentParamSchedule();
    }

    @Override
    public void onRequestFinishReclaim() {
        showToast("已通知服务器完成灌装");
        ProjectManager.getInstance().setFinishCollect(true);
        initOperateByProgress();
    }

    private void operateDoor() {
        String[] door_items = new String[]{getString(R.string.open_door), getString(R.string.close_door), getString(R.string.read), getString(R.string.stop)};
        DialogFragmentHelper.showMultipleOperateDialog(this, getString(R.string.door), null, door_items, new IDialogResultListener<Integer>() {
            @Override
            public void onDataResult(Integer result) {
                if (result == 0) {
                    presenter.openDoor();
                } else if (result == 1) {
                    presenter.closeDoor();
                } else if (result == 2) {
                    presenter.readDoor();
                } else if (result == 3) {
                    presenter.stopDoor();
                }
            }
        }, true, true);
    }

    private void operateShakeDoor() {
        DialogFragmentHelper.showTwoOperateDialog(this, "摇床", "", R.string.open, R.string.close, new IDialogResultListener<Integer>() {
            @Override
            public void onDataResult(Integer result) {
                if (DialogInterface.BUTTON_POSITIVE == result) {
                    presenter.startShakeTable();
                } else if (DialogInterface.BUTTON_NEGATIVE == result) {
                    presenter.stopShakeTable();
                }
            }
        }, true);
    }

    private void operateChangeAir() {
        DialogFragmentHelper.showTwoOperateDialog(this, "换气", "", R.string.open, R.string.close, new IDialogResultListener<Integer>() {
            @Override
            public void onDataResult(Integer result) {
                if (DialogInterface.BUTTON_POSITIVE == result) {
                    presenter.openCultureTank(ParamsPreferences.getInstance().getCultureTankSpeed());
                } else if (DialogInterface.BUTTON_NEGATIVE == result) {
                    presenter.closeCultureTank();
                }
            }
        }, true);
    }

    private boolean isFullScreen=false;
    private void fullScreenToggle(){
        if (!isFullScreen) {
            Intent intent = new Intent();
            intent.setAction("com.norco.removebar");
            ExperimentActivity.this.sendBroadcast(intent);
            isFullScreen=true;
        } else {
            Intent intent = new Intent();
            intent.setAction("com.norco.addbar");
            ExperimentActivity.this.sendBroadcast(intent);
            isFullScreen=false;
        }
    }


    private void onChangeLiquidPlan() {
        ChangeLiquidPlanListFrag changeLiquidPlanListFrag = new ChangeLiquidPlanListFrag();
        changeLiquidPlanListFrag.show(fragmentManager, null);
    }

    private void onRawMaterial() {
        final RawMaterialDF rawMaterialDF = new RawMaterialDF();
        rawMaterialDF.setConfirmRawMaterial(new RawMaterialFrag.ConfirmRawMaterial() {
            @Override
            public void onConfirmRawMaterial() {
                rawMaterialDF.dismiss();
                setCornerIndex(btn_materialConfirm, 1);
                showCornerIndex(btn_materialConfirm, getString(R.string.rawMaterialConfirm), (Integer) btn_materialConfirm.getTag());
            }
        });
        rawMaterialDF.show(fragmentManager, null);
    }

    //设置角标
    private void setCornerIndex(TextView textView, int increase) {
        if (textView == null) {
            return;
        }
        if (textView.getTag() != null) {
            int times = (int) textView.getTag();
            textView.setTag(times + increase);
        } else {
            textView.setTag(1);
        }
    }

    //显示角标
    private void showCornerIndex(TextView textView, String text, int cornerIndex) {
//        StringBuilder stringBuilder=new StringBuilder();
//        stringBuilder.append(text);
//        if(cornerIndex!=0){
//            stringBuilder.append(cornerIndex);
//        }
//        SpannableString spannableString = new SpannableString(stringBuilder.toString());
//        if(cornerIndex>0) {
//            int length=text.length();
//            spannableString.setSpan(new RelativeSizeSpan(0.5f), length, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//一半大小
//            spannableString.setSpan(new SuperscriptSpan(), length, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//上标
//        }
//        textView.setText(spannableString);

        if (cornerIndex == 0) {
            textView.setText(text);
        } else {
            textView.setText(Html.fromHtml(text + "<sup>" + cornerIndex + "</sup>"));
        }
    }

    @OnClick({R.id.btn_adjustTemperature, R.id.btn_adjustWeight, R.id.btn_console, R.id.changeLiquidPlan, R.id.nextDay, R.id.btn_door, R.id.btn_closeSchedule, R.id.btn_force_test, R.id.btn_environment_control, R.id.rawMaterial})
    public void onTestClick(View view) {
        switch (view.getId()) {
            case R.id.btn_adjustTemperature:
                AdjustTemperatureDF adjustTemperatureDF = new AdjustTemperatureDF();
                adjustTemperatureDF.show(fragmentManager, null);
                break;
            case R.id.btn_adjustWeight:
                DialogFragmentHelper.showConfirmDialog(this, "", "校准称重时请停止所有称重相关的操作！", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            AdjustWeightDF adjustWeightDF = new AdjustWeightDF();
                            adjustWeightDF.show(fragmentManager, null);
                        }
                    }
                }, true);
                break;
            case R.id.btn_console:
                onConsole();
                break;
            case R.id.changeLiquidPlan:
                onChangeLiquidPlan();
                break;
            case R.id.nextDay:
                ExperimentStageManager.getInstance().forwardStage();
                moveToStage(ExperimentStageManager.getInstance().getCurrentStage());
                break;
            case R.id.btn_door:
                operateDoor();
                break;
            case R.id.btn_closeSchedule:
                final boolean isScheduleTaskClose = presenter.isScheduleTaskClose();
                String string = isScheduleTaskClose ? "开启" : "关闭";
                int operate = isScheduleTaskClose ? R.string.open : R.string.close;
                DialogFragmentHelper.showTwoOperateDialog(this, "环境参数读取", "", R.string.open, R.string.close, new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            startReadEnvironmentSchedule();
//                            if (isScheduleTaskClose) {
//                                startReadEnvironmentSchedule();
//                            } else {
//                                presenter.cancelAllTask();
//                            }
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.cancelAllTask();
                        }
                    }
                }, true);
                break;
            case R.id.btn_force_test:
                ForceTestDF forceTestDF = new ForceTestDF();
                forceTestDF.show(fragmentManager, null);
                break;
            case R.id.btn_environment_control:
                DialogFragmentHelper.showThreeOperateDialog(this, getString(R.string.EnvironmentControl), null, R.string.stopHeat, R.string.stopCO2, R.string.stopO2, new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            presenter.closeHeat();
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                            presenter.closeCO2();
                        } else if (result == DialogInterface.BUTTON_NEUTRAL) {
                            presenter.closeO2();
                        }
                    }
                });
                break;
            case R.id.rawMaterial:
                onRawMaterial();
                break;
        }
    }

    //根据选择的操作，执行操作
//    private void operateFluidIntake(int operateId, int amount) {
//        if (operateId == R.string.fluidIntake) {
//            presenter.fluidIntake(amount);
//        } else if (operateId == R.string.resume) {
//            presenter.resumePeristalticPump(PeristalticPumpBO.PeristalticPump_fluidIntake);
//        } else if (operateId == R.string.pause) {
//            presenter.pausePeristalticPump(PeristalticPumpBO.PeristalticPump_fluidIntake);
//        } else if (operateId == R.string.end) {
//            presenter.endPeristalticPump(PeristalticPumpBO.PeristalticPump_fluidIntake);
//        }
//    }

    //根据选择的操作，执行操作
    private void operatePumpTask(int operateId, byte ModularNO) {
//        if (operateId == R.string.run) {
//            if (ModularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
//                presenter.fluidIntake(amount);
//            } else if (ModularNO == PeristalticPumpBO.PeristalticPump_waste) {
//                presenter.discharge(amount);
//            } else if (ModularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
//                presenter.collect(amount);
//            }
//        } else
        if (operateId == R.string.resume) {
            presenter.resumePeristalticPump(ModularNO);
        } else if (operateId == R.string.pause) {
            presenter.pausePeristalticPump(ModularNO);
        } else if (operateId == R.string.end) {
            presenter.endPeristalticPump(ModularNO);
        }
    }

//    private void operateCollect(int operateId, int amount) {
//        if (operateId == R.string.exp_collect) {
//            presenter.discharge(amount);
//        } else if (operateId == R.string.resume) {
//            presenter.resumePeristalticPump(PeristalticPumpBO.PeristalticPump_reclaim);
//        } else if (operateId == R.string.pause) {
//            presenter.pausePeristalticPump(PeristalticPumpBO.PeristalticPump_reclaim);
//        } else if (operateId == R.string.end) {
//            presenter.endPeristalticPump(PeristalticPumpBO.PeristalticPump_reclaim);
//        }
//    }

    private int getOperateResId(int status) {
        return R.string.run;
//        int operateId;
//        switch (status) {
//            case OperateTask.STATE_UNSTART:
//            case OperateTask.STATE_STARTING:
//            case OperateTask.STATE_END:
//                operateId = R.string.run;
//                break;
//            case OperateTask.STATE_PAUSE:
//            case OperateTask.STATE_RESUMEING:
//                operateId = R.string.resume;
//                break;
//            case OperateTask.STATE_STARTED:
//            case OperateTask.STATE_PAUSEING:
//            case OperateTask.STATE_RESUMED:
//                operateId = R.string.pause;
//                break;
//            case OperateTask.STATE_ENDING:
//                operateId = R.string.end;
//                break;
//            default:
//                operateId = R.string.run;
//                break;
//        }
//        return operateId;
    }

    private void sample() {
        sampleDF = new SampleDF();
        sampleDF.setOnSample(ExperimentActivity.this);
        sampleDF.show(fragmentManager, null);
    }

//    private void injection() {
//        injectionDF = new InjectionDF();
//        injectionDF.setOnInject(ExperimentActivity.this);
//        injectionDF.show(fragmentManager, null);
//    }

    //在操作进液泵前判断状态是否可以操作，是否已经有任务在操作
//    private String checkPump(byte pumpNO) {
//        GifDrawable gifDrawable = null;
//        String pump = null;
//        if (pumpNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
//            gifDrawable = gifD_FluidIntake;
//        } else if (pumpNO == PeristalticPumpBO.PeristalticPump_circulating) {
//            gifDrawable = gifD_Circulating;
//        } else if (pumpNO == PeristalticPumpBO.PeristalticPump_waste) {
//            gifDrawable = gifD_Waste;
//        } else if (pumpNO == PeristalticPumpBO.PeristalticPump_reclaim) {
//            gifDrawable = gifD_Reclaim;
//        } else {
//            return null;
//        }
//        if (gifDrawable.isPlaying()) {
//            StringBuilder err = new StringBuilder();
//            err.append(getString(PeristalticPumpBO.getModularNOStrByCode(pumpNO)));
//            err.append("正在运行，");
//            err.append("请先关闭再操作。");
//            return err.toString();
//        } else {
//            return null;
//        }
//    }

    private void setTitle(int day, String progress) {
        tv_title.setText(String.format("Day%d %s", day, progress));
    }

    //初始培养液泵入完成
    @Override
    public void onInitCultureLiquidFinish() {
        showToast("初始培养液泵入完成");
        inputLiquidLoading.setVisibility(View.GONE);
//        initStirrerCirclingPumpAtStart();

//        presenter.openStirrerTask(ParamsPreferences.getInstance().getStirrerSpeed());
//        presenter.openPumpTask(PeristalticPumpBO.PeristalticPump_circulating, ParamsPreferences.getInstance().getCirculatingPumpSpeed(), ParamsPreferences.getInstance().getCirculatingPumpDirection(),null);
    }

    @Override
    public void onStartCultureSucc() {
        showDialogMessage("细胞培养开始啦！");
//        btn_start_culture.setVisibility(View.GONE);
//        btn_pause_culture.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPauseCultureSucc() {
        showDialogMessage("细胞培养暂停啦！");
//        btn_pause_culture.setVisibility(View.GONE);
//        btn_resume_culture.setVisibility(View.VISIBLE);
    }

    @Override
    public void onResumeCultureSucc() {
        showDialogMessage("细胞培养恢复啦！");
//        btn_pause_culture.setVisibility(View.VISIBLE);
//        btn_resume_culture.setVisibility(View.GONE);
    }

    @Override
    public void liquidLevelWarning() {
        tv_level_warning.setText("液位异常");
//        showToast("液位异常");
    }

    @Override
    public void liquidLevelOk() {
        tv_level_warning.setText("液位正常");
    }

    private boolean isParamsInRange(double param, double setting, double error) {
        if (param >= setting - error && param <= setting + error) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onReceiveCO2(double CO2) {
        double settedCO2;
        if (CO2Controller.getInstance().getSettedValue() == null) {
            settedCO2 = 0;
        } else {
            settedCO2 = CO2Controller.getInstance().getSettedValue();
        }

        String CO2Str = String.format("%.01f", CO2);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(CO2Str);
        spannableStringBuilder.append("%");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.format("%.01f", settedCO2));
        spannableStringBuilder.append("%");

        ForegroundColorSpan colorSpan_current;
        if (isParamsInRange(CO2, settedCO2, ParamConsts.CO2_error)) {
            iv_CO2_warning.setVisibility(View.INVISIBLE);
            colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        } else {
            iv_CO2_warning.setVisibility(View.VISIBLE);
            colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        }
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, CO2Str.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, CO2Str.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvCO2.setText(spannableStringBuilder);

    }

    @Override
    public void onReceiveO2(double O2) {
        double settedO2;
        if (O2Controller.getInstance().getSettedValue() == null) {
            settedO2 = 0;
        } else {
            settedO2 = O2Controller.getInstance().getSettedValue();
        }

        String O2Str = String.format("%.01f", O2);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(O2Str);
        spannableStringBuilder.append("%");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.format("%.01f", settedO2));
        spannableStringBuilder.append("%");

        ForegroundColorSpan colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, O2Str.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, O2Str.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvO2.setText(spannableStringBuilder);
        if (isParamsInRange(O2, settedO2, ParamConsts.O2_error)) {
            iv_O2_warning.setVisibility(View.INVISIBLE);
        } else {
            iv_O2_warning.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onReceiveTemperature(double temperature) {
        double settedTemperature;
        if (TemperatureController.getInstance().getSettedValue() == null) {
            settedTemperature = 0;
        } else {
            settedTemperature = TemperatureController.getInstance().getSettedValue();
        }

        String temperatureStr = String.format("%.01f", temperature);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(temperatureStr);
        spannableStringBuilder.append("℃");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.format("%.01f", settedTemperature));
        spannableStringBuilder.append("℃");

        ForegroundColorSpan colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, temperatureStr.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, temperatureStr.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvTemperature.setText(spannableStringBuilder);
        if (isParamsInRange(temperature, settedTemperature, ParamConsts.temperature_error)) {
            iv_temperature_warning.setVisibility(View.INVISIBLE);
        } else {
            iv_temperature_warning.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void readCO2Failed() {
        double settedCO2;
        if (CO2Controller.getInstance().getSettedValue() == null) {
            settedCO2 = 0;
        } else {
            settedCO2 = CO2Controller.getInstance().getSettedValue();
        }

        String CO2Str = "??";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(CO2Str);
//        spannableStringBuilder.append("%");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.valueOf(settedCO2));
        spannableStringBuilder.append("%");

        iv_CO2_warning.setVisibility(View.VISIBLE);
        ForegroundColorSpan colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, CO2Str.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, CO2Str.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvCO2.setText(spannableStringBuilder);
        Log.i(TAG, spannableStringBuilder.toString());
    }

    @Override
    public void readO2Failed() {
        double settedO2;
        if (O2Controller.getInstance().getSettedValue() == null) {
            settedO2 = 0;
        } else {
            settedO2 = O2Controller.getInstance().getSettedValue();
        }

        String O2Str = String.valueOf("??");
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(O2Str);
//        spannableStringBuilder.append("%");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.valueOf(settedO2));
        spannableStringBuilder.append("%");

        iv_O2_warning.setVisibility(View.VISIBLE);
        ForegroundColorSpan colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, O2Str.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, O2Str.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvO2.setText(spannableStringBuilder);
    }

    @Override
    public void readTemperatureFailed() {
        double settedTemperature;
        if (TemperatureController.getInstance().getSettedValue() == null) {
            settedTemperature = 0;
        } else {
            settedTemperature = TemperatureController.getInstance().getSettedValue();
        }

        String temperatureStr = "??";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(temperatureStr);
//        spannableStringBuilder.append("℃");
        spannableStringBuilder.append("/");
        spannableStringBuilder.append(String.valueOf(settedTemperature));
        spannableStringBuilder.append("℃");

        iv_temperature_warning.setVisibility(View.VISIBLE);
        ForegroundColorSpan colorSpan_current = new ForegroundColorSpan(getResources().getColor(R.color.param_current));
        ForegroundColorSpan colorSpan_setting = new ForegroundColorSpan(getResources().getColor(R.color.param_setting));
        spannableStringBuilder.setSpan(colorSpan_current, 0, temperatureStr.length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableStringBuilder.setSpan(colorSpan_setting, temperatureStr.length() + 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        tvTemperature.setText(spannableStringBuilder);
    }

    @Override
    public void setO2Failed() {
        showToast("设置O2失败");
    }

    @Override
    public void setTemperatureFailed() {
        showToast("设置温度失败");
    }

    @Override
    public void setCO2Failed() {
        showToast("设置CO2失败");
    }

    @Override
    public void onSetCO2(double CO2) {
        showToast(String.format("设置CO2成功：%.1f", CO2));
    }

    @Override
    public void onSetO2(double O2) {
        showToast(String.format("设置O2成功：%.1f", O2));
    }

    @Override
    public void onSetTemperature(double temperature) {
        showToast(String.format("设置温度成功：%.1f", temperature));
    }

    @Override
    public void peelSucc(byte[] ad) {
        tv_weight.setText("去皮成功");
        showToast("AD: " + ByteUtils.getHexByte(ad, 0, ad.length));
//        tv_electronic_scal.setText("去皮成功");
//        showToast("去皮成功");
    }

    @Override
    public void weightSucc(double weight) {
        tv_weight.setText(String.format("%.0f克", weight));
        setTankProgress((int) weight);
//        tv_electronic_scal.setText(String.format("%f克",weight));
//        showToast("称重：" + weight);
    }

    @Override
    public void peelFail() {
        tv_weight.setText("去皮失败");
    }

    @Override
    public void weightFail() {
        tv_weight.setText("称重失败");
    }

    @Override
    public void weightAfterDischarge(int flow, double weight) {
        showDialogMessage("排液" + flow + "ml" + "，称重" + weight + " 请校验！");
    }

    @Override
    public void onTerminateFluidIntaken() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialogMessage("进液任务终止！");
                if(liquidControlDF!=null){
                    liquidControlDF.dismiss();
                    liquidControlDF=null;
                }
            }
        });
    }

    @Override
    public void onTerminateDischarge() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialogMessage("排液任务终止！");
                if(liquidControlDF!=null){
                    liquidControlDF.dismiss();
                    liquidControlDF=null;
                }
            }
        });
    }

    @Override
    public void onTerminateCollect() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialogMessage("罐装任务终止！");
                if(liquidControlDF!=null){
                    liquidControlDF.dismiss();
                    liquidControlDF=null;
                }
            }
        });
    }

    @Override
    public void onTerminateCleanPipe() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialogMessage("清洗管路任务终止！");
               if(cleanPipesDF!=null){
                   cleanPipesDF.dismiss();
                   cleanPipesDF=null;
               }
            }
        });
    }

    @Override
    public void onTerminateChangeLiquid() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialogMessage("置换任务终止！");
                if(changeLiquidTXDF!=null){
                    changeLiquidTXDF.dismiss();
                    changeLiquidTXDF=null;
                }
                if(concentrationReplacementDF!=null){
                    concentrationReplacementDF.dismiss();
                    concentrationReplacementDF=null;
                }
            }
        });
    }

    @Override
    public void finishFluidIntaken() {
        showDialogMessage("补液完成");
        fluidIntakeLoading.setVisibility(View.GONE);
        if(liquidControlDF!=null){
            liquidControlDF.dismiss();
            liquidControlDF=null;
        }
    }

    @Override
    public void finishFluidIntakenCell() {
        if (isAddCell) {
            if (addCellDF != null) {
                addCellDF.finishAddCell();
                addCellDF = null;
            }
            isAddCell = false;
        }
    }

    @Override
    public void finishFluidIntakenViruses() {
        if (isAddViruses) {
            if (addVirusesDF != null) {
                addVirusesDF.finishAddViruses();
                addVirusesDF = null;
            }
            isAddViruses = false;
        }
    }

    @Override
    public void finishFluidIntakenCryoprotectant() {
        showDialogMessage("添加冻存保护剂完成");
        addCryoprotectantLoading.setVisibility(View.GONE);
        if(liquidControlDF!=null){
            liquidControlDF.dismiss();
            liquidControlDF=null;
        }
    }

    @Override
    public void finishCollect() {
        showDialogMessage("收集完成");
        collectLoading.setVisibility(View.GONE);
        if(liquidControlDF!=null){
            liquidControlDF.dismiss();
            liquidControlDF=null;
        }
    }

    @Override
    public void finishDischarge() {
        showDialogMessage("排液完成");
        dischargeLoading.setVisibility(View.GONE);
        if(liquidControlDF!=null){
            liquidControlDF.dismiss();
            liquidControlDF=null;
        }
    }

    @Override
    public void onDoorOpen() {
        showToast("门正在打开");
    }

    @Override
    public void onDoorColse() {
        showToast("门正在关闭");
    }

    @Override
    public void onDoorStop() {
        showToast("门停止");
    }

    @Override
    public void onReadDoor(String statusStr) {
        showToast(statusStr);
    }

    private synchronized boolean isAllRunnedPumpStop() {
        boolean isAllStop = presenter.isPumpStoped(PeristalticPumpBO.PeristalticPump_fluidIntake) && presenter.isPumpStoped(PeristalticPumpBO.PeristalticPump_waste) && presenter.isPumpStoped(PeristalticPumpBO.PeristalticPump_circulating) && presenter.isPumpStoped(PeristalticPumpBO.PeristalticPump_reclaim);
        return isAllStop;
    }

    @Override
    public void onOpenFluidIntakePumpSucc(int speed) {
        if (speed > 0) {
            gifD_FluidIntake.start();
        }
//        setSpeed(tvPumpFluidIntakeState, speed);
        //进液是要检测液位
//        presenter.activateLiquidLevelAlarm();
        //因为之前要进样而暂停的进样任务，重新恢复
        if (isIntakeNeedResumeAfterSample) {
            isIntakeNeedResumeAfterSample = false;
        }
//        if (isInjecting) {
//            if (presenter.isReadyForInject()) {
//                if (injectionDF != null) {
//                    injectionDF.startInjectionOK();
//                }
//            }
//        }
    }

    @Override
    public void onCloseFluidIntakePumpSucc() {
//        synchronized (lock_FluidIntake) {
        gifD_FluidIntake.stop();
        setSpeed(tvPumpFluidIntakeState, 0);
//        }
        //进液结束，停止检测液位
        presenter.stopActivateLiquidLevelAlarm();

//        if (isInjecting) {
//            if (injectionDF != null) {
//                injectionDF.finishInject();
//            }
//            isInjecting = false;
//        }
    }

    @Override
    public void onReadFluidIntake(byte direction, int speed, String alarmStr) {
        if (TextUtils.isEmpty(alarmStr)) {
//            synchronized (lock_FluidIntake) {
            if (gifD_FluidIntake.isPlaying()) {
                setSpeed(tvPumpFluidIntakeState, speed);
            } else {
                setSpeed(tvPumpFluidIntakeState, 0);
            }
//            }
        } else {
            showPumpError(tvPumpFluidIntakeState, alarmStr);
        }
    }

    @Override
    public void onFluidIntakePumpAlarm(String alarmStr) {
//        synchronized (lock_FluidIntake) {
        gifD_FluidIntake.stop();
//        }
        showPumpError(tvPumpFluidIntakeState, alarmStr);
        presenter.stopActivateLiquidLevelAlarm();
    }

    @Override
    public void onFluidIntakePumpAlarmDismiss(int speed) {
//        presenter.resumePumpAfterAlarmDismiss(PeristalticPumpBO.PeristalticPump_fluidIntake);
//        synchronized (lock_FluidIntake) {
        if (speed > 0) {
            gifD_FluidIntake.start();
//            presenter.activateLiquidLevelAlarm();
        } else {
            gifD_FluidIntake.stop();
        }
        setSpeed(tvPumpFluidIntakeState, speed);
//        }
    }

    @Override
    public void onOpenWastePumpSucc(int speed) {
        if (speed > 0) {
            gifD_Waste.start();
        }
//        setSpeed(tvPumpWasteState, speed);
        if (isWasteNeedResumeAfterSample) {
            isWasteNeedResumeAfterSample = false;
        }
    }

    @Override
    public void onCloseWastePumpSucc() {
//        synchronized (lock_Waste) {
        gifD_Waste.stop();
        setSpeed(tvPumpWasteState, 0);
//        }
        //因为要进样取样而暂停进样任务，暂停成功后开始进样取样
//        if (isSampling && sampleDF != null) {
//            if (isAllRunnedPumpStop()) {
//                sampleDF.startSampleOK();
//                hideLoading();
//            }
//        }
    }

    @Override
    public void onReadWaste(byte direction, int speed, String alarmStr) {
        if (TextUtils.isEmpty(alarmStr)) {
//            synchronized (lock_Waste) {
            if (gifD_Waste.isPlaying()) {
                setSpeed(tvPumpWasteState, speed);
            } else {
                setSpeed(tvPumpWasteState, 0);
            }
//            }
        } else {
            showPumpError(tvPumpWasteState, alarmStr);
        }
    }

    @Override
    public void onWastePumpAlarm(String alarmStr) {
//        synchronized (lock_Waste) {
        gifD_Waste.stop();
//        }
        showPumpError(tvPumpWasteState, alarmStr);
    }

    @Override
    public void onWastePumpAlarmDismiss(int speed) {
//        synchronized (lock_Waste) {
        if (speed > 0) {
            gifD_Waste.start();
        } else {
            gifD_Waste.stop();
        }
        setSpeed(tvPumpWasteState, speed);
//        }
    }

    @Override
    public void onOpenCirclePumpSucc(int speed) {
        if (speed > 0) {
            gifD_Circulating.start();
        }
//        setSpeed(tvPumpCirculatingState, speed);
        if (isCircleNeedResumeAfterSample) {
            isCircleNeedResumeAfterSample = false;
        }
        if (isSampling) {
            if (presenter.isReadyForSample()) {
                if (sampleDF != null) {
                    sampleDF.startSampleOK();
                }
            }
        }
    }

    @Override
    public void onCloseCirclePumpSucc() {
        gifD_Circulating.stop();
        setSpeed(tvPumpCirculatingState, 0);
//        if (isInjecting) {
//            if (presenter.isReadyForInject()) {
//                if (injectionDF != null) {
//                    injectionDF.startInjectionOK();
//                }
//            }
//        }
    }

    @Override
    public void onReadCircling(byte direction, int speed, String alarmStr) {
        if (TextUtils.isEmpty(alarmStr)) {
//            synchronized (lock_Circulating) {
            if (gifD_Circulating.isPlaying()) {
                setSpeed(tvPumpCirculatingState, speed);
            } else {
                setSpeed(tvPumpCirculatingState, 0);
            }
//            }
        } else {
            showPumpError(tvPumpCirculatingState, alarmStr);
        }
    }

    @Override
    public void onCirclingPumpAlarm(String alarmStr) {
//        synchronized (lock_Circulating) {
        gifD_Circulating.stop();
//        }
        showPumpError(tvPumpCirculatingState, alarmStr);
    }

    @Override
    public void onCirclingPumpAlarmDismiss(int speed) {
//        synchronized (lock_Circulating) {
        if (speed > 0) {
            gifD_Circulating.start();
        } else {
            gifD_Circulating.stop();
        }
        setSpeed(tvPumpCirculatingState, speed);
//        }
    }

    @Override
    public void onOpenReclaimPumpSucc(int speed) {
        if (speed > 0) {
            gifD_Reclaim.start();
        }
//        setSpeed(tvPumpReclaimState, speed);
        if (isReclaimNeedResumeAfterSample) {
            isReclaimNeedResumeAfterSample = false;
        }
    }

    @Override
    public void onCloseReclaimPumpSucc() {
//        synchronized (lock_Reclaim) {
        gifD_Reclaim.stop();
        setSpeed(tvPumpReclaimState, 0);
//        }
        //因为要进样取样而暂停进样任务，暂停成功后开始进样取样
//        if (isSampling && sampleDF != null) {
//            if (isAllRunnedPumpStop()) {
//                sampleDF.startSampleOK();
//                hideLoading();
//            }
//        }
    }

    @Override
    public void onReadReclaim(byte direction, int speed, String alarmStr) {
        if (TextUtils.isEmpty(alarmStr)) {
//            synchronized (lock_Reclaim) {
            if (gifD_Reclaim.isPlaying()) {
                setSpeed(tvPumpReclaimState, speed);
            } else {
                setSpeed(tvPumpReclaimState, 0);
            }
//            }
        } else {
            showPumpError(tvPumpReclaimState, alarmStr);
        }
    }

    @Override
    public void onReclaimPumpAlarm(String alarmStr) {
//        synchronized (lock_Reclaim) {
        gifD_Reclaim.stop();
//        }
        showPumpError(tvPumpReclaimState, alarmStr);
    }

    @Override
    public void onReclaimPumpAlarmDismiss(int speed) {
//        synchronized (lock_Reclaim) {
        if (speed > 0) {
            gifD_Reclaim.start();
        } else {
            gifD_Reclaim.stop();
        }
        setSpeed(tvPumpReclaimState, speed);
//        }
    }

    @Override
    public void onChangeLiquidSucc() {
        showDialogMessage("置换第" + changeLiquidTurn + "轮成功");
        changeLiquidLoading.setVisibility(View.GONE);
        concentrationReplacementLoading.setVisibility(View.GONE);
        changeLiquidTurn++;
        if(changeLiquidTXDF!=null){
            changeLiquidTXDF.dismiss();
            changeLiquidTXDF=null;
        }
        if(concentrationReplacementDF!=null){
            concentrationReplacementDF.dismiss();
            concentrationReplacementDF=null;
        }
//        if(changeLiquidTurn<3) {
//            ChangeLiquidTXDF changeLiquidTXDF = ChangeLiquidTXDF.newInstance(presenter.getChangeLiquidTask());
//            changeLiquidTXDF.setOnChangeLiquid(onChangeLiquid);
//        }else {
//            changeLiquidTurn=0;
//        }
    }

    @Override
    public void cleanPipefinishOne(String taskName) {
        showToast("完成一次" + taskName);
    }

    @Override
    public void cleanPipefinishAll(String taskName) {
        showDialogMessage(taskName + "全部完成");
        cleanPipeLoading.setVisibility(View.GONE);
        if(cleanPipesDF!=null){
            cleanPipesDF.dismiss();
            cleanPipesDF=null;
        }
//        showToast(taskName+"全部完成");
//        promoteInitCultureLiquid();
    }

    private void setSpeed(TextView textView, int speed) {
        if (textView == null) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(speed);
        stringBuilder.append(" ");
        stringBuilder.append(getString(R.string.speed_unit));
        textView.setText(stringBuilder.toString());
    }

    private void showPumpError(TextView textView, String error) {
        if (textView == null) {
            return;
        }
        textView.setText(error);
    }

//    @Override
//    public void onClosePumpSucc(byte modularNO) {
//        if (modularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
//            gifD_FluidIntake.stop();
//            setSpeed(tvPumpFluidIntakeState, 0);
//        } else if (modularNO == PeristalticPumpBO.PeristalticPump_circulating) {
//            gifD_Circulating.stop();
//            setSpeed(tvPumpCirculatingState, 0);
//        } else if (modularNO == PeristalticPumpBO.PeristalticPump_waste) {
//            gifD_Waste.stop();
//            setSpeed(tvPumpWasteState, 0);
//        } else if (modularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
//            gifD_Reclaim.stop();
//            setSpeed(tvPumpReclaimState, 0);
//        }
//    }

    @Override
    public void onError(String err) {
        showDialogMessage(err);
    }

    @Override
    public void onOpenStirrerSucc(int speed) {
        showToast("磁力搅拌器启动成功，速度" + speed);
        setSpeed(tvStirrerState, speed);
        if (speed > 0) {
            gifDMagneticStirrer.start();
            wv_tank.setSurface(WaveView.Surface_wave);
        }
    }

    @Override
    public void onCloseStirrerSucc() {
        showToast("磁力搅拌器关闭成功");
        setSpeed(tvStirrerState, 0);
        gifDMagneticStirrer.stop();
        wv_tank.setSurface(WaveView.Surface_calm);
//        if (isInjecting) {
//            if (presenter.isReadyForInject()) {
//                if (injectionDF != null) {
//                    injectionDF.startInjectionOK();
//                }
//            }
//        }
    }

    @Override
    public void onOpenUltravioletLightSucc() {
        showToast("紫外线灯打开成功");
//        UltravioletLight.setTag(true);
//        UltravioletLight.setImageResource(R.drawable.ultraviolet_light_on);
        UltravioletLight_wick.setVisibility(View.VISIBLE);
    }

    @Override
    public void onCloseUltravioletLightSucc() {
        showToast("紫外线灯关闭成功");
//        UltravioletLight.setTag(false);
//        UltravioletLight.setImageResource(R.drawable.ultraviolet_light_off);
        UltravioletLight_wick.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onOpenCultureTankSucc(int speed) {
        showToast("培养罐换气泵打开成功" + ",速度：" + speed);
        setSpeed(tvCultureTankState, speed);
        if (speed > 0) {
            gifDCultureTank.start();
        }
    }

    @Override
    public void onCloseCultureTankSucc() {
        showToast("培养罐换气泵关闭成功");
        setSpeed(tvCultureTankState, 0);
        gifDCultureTank.stop();
    }

    @Override
    public void onOpenIncubatorSucc() {
        showToast("培养箱换气泵打开成功");
        gifDIncubator.start();
    }

    @Override
    public void onCloseIncubatorSucc() {
        showToast("培养箱换气泵关闭成功");
        gifDIncubator.stop();
    }

    @Override
    public void onSalineOpen() {
        showToast("生理盐水电磁阀打开");
    }

    @Override
    public void onSalineClose() {
        showToast("生理盐水电磁阀关闭");
//        if (isInjecting) {
//            if (presenter.isReadyForInject()) {
//                if (injectionDF != null) {
//                    injectionDF.startInjectionOK();
//                }
//            }
//        }
    }

    @Override
    public void onMediumOpen() {
        showToast("培养基电磁阀打开");
    }

    @Override
    public void onMediumClose() {
        showToast("培养基电磁阀关闭");
//        if (isInjecting) {
//            if (presenter.isReadyForInject()) {
//                if (injectionDF != null) {
//                    injectionDF.startInjectionOK();
//                }
//            }
//        }
    }

    @Override
    public void onShakerOpen() {
        showToast("摇床打开");
    }

    @Override
    public void onShakerClose() {
        showToast("摇床关闭");
    }

    @Override
    public void onStartNewProject() {
        Intent intent = new Intent(ExperimentActivity.this, PreProcessingActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        presenter.stopScheduleReadCO2();
        presenter.stopScheduleReadO2();
        presenter.stopScheduleReadTemperature();
        presenter.stopScheduleWeight();
        presenter.stopActivateLiquidLevelAlarm();
        presenter.deActiveDetectPumpFluidIntak();
        presenter.deActiveDetectPumpCircling();
        presenter.deActiveDetectPumpReclaim();
        presenter.deActiveDetectPumpWaste();
        presenter.cancelScheduleRequestEnvironmentParams();
//        ThreadPoolProxyFactory.getSerialPortThreadPoolProxy().shutDown(true);
//        stopService(new Intent(this, CommandService.class));
        presenter.detachView();
        super.onDestroy();
    }

//    @Override
//    public void injectStart(Injection injection) {
//        isInjecting = true;
////        if (presenter.isReadyForInject()) {
////            if (injectionDF != null) {
////                injectionDF.startInjectionOK();
////            }
////        } else {
////            //关闭生理盐水电磁阀
////            if (SalineValveController.getInstance().getStatus() != ValveBO.close) {
////                presenter.closeSalineValve();
////            }
////            //关闭培养基电磁阀
////            if (MediumValveController.getInstance().getStatus() != ValveBO.close) {
////                presenter.openMediumValve();
////            }
////            //停止循环泵
////            if (CirculatingPumpController.getInstance().getSpeed() != 0) {
////                presenter.closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
////            }
////            //停止磁力搅拌器
////            if (MagneticStirrerController.getInstance().getSpeed() != 0) {
////                presenter.closeStirrerTask(null);
////            }
////            //打开进液泵
////            if (FluidIntakePumpController.getInstance().getSpeed() == 0) {
////                presenter.openPumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), ParamsPreferences.getInstance().getFluidIntakePumpDirection(), null);
////            }
////        }
//        if (injectionDF != null) {
//            onAddCell(injection.getTotalVolume(), ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), "添加细胞", injection.getStartDate());
//            showToast("开始添加");
//            injectionDF.startInjectionOK();
//            presenter.requestOperationLog(getString(R.string.addCell), "");
//            setCornerIndex(btn_add_cell, 1);
//            showCornerIndex(btn_add_cell, getString(R.string.addCell), (Integer) btn_add_cell.getTag());
//        }
//    }
//
//    @Override
//    public void sour() {
//        presenter.scourAfterInjection();
//    }
//
//    @Override
//    public void injectFinish() {
////        isInjecting = false;
//        //有暂停的任务，则恢复任务，冲刷
////        if (presenter.isPumpPaused(PeristalticPumpBO.PeristalticPump_fluidIntake)) {
////            //计算出进液最小冲刷量需要的时间
////            double minTime = UtilHelpers.calculateTimeBySpeedFlow(presenter.getFluidIntakenPumpSpeed(), ParamConsts.scourAfterInjection);
////            double leftTime = presenter.getLeftTime(PeristalticPumpBO.PeristalticPump_fluidIntake);
////            showToast("leftTime " + leftTime + "minTime " + minTime);
////            if (leftTime < minTime) {//剩余进液时间小于冲刷需要的时间
////                //重新设置progressBar的MAX
////                setPorgress1Max(getProgress1Max() + (int) Math.round(minTime - leftTime));
////                showToast("剩余进液量小于冲刷量（100ml）,强制进液100ml冲刷");
////                presenter.editAmountForPausedTask(PeristalticPumpBO.PeristalticPump_fluidIntake, ParamConsts.scourAfterInjection);
////            } else {
////                presenter.resumePeristalticPump(PeristalticPumpBO.PeristalticPump_fluidIntake);
////            }
////        } else {//没有任务，则直接进液100ml冲刷
////            presenter.scourAfterInjection();
////            showToast("进液100ml冲刷");
////        }
////        showToast("进样完成");
//        //冲刷
//        presenter.scourAfterInjection();
//    }

//    @Override
//    public void saveInjectData(Injection injection) {
//        presenter.saveInjectionData(injection);
//        showToast("保存进样信息成功");
//        //记录进样
//        Operation operation = new Operation();
////        operation.setData(injection.getCellAmount()+"ml");
//        operation.setData(injection.getCellVolume() + "ml");
//        operation.setDateTime(new Date());
//        operation.setName(Operation.Operate_Inject);
//        operation.setOperator("登陆者");
//        presenter.saveOperation(operation);
//    }

    @Override
    public void onSourFinish() {
//        if (injectionDF != null) {
//            injectionDF.finishSour();
//        }

        showDialogMessage("冲刷完成");
//        if(isAddCell) {
//            showDialogMessage("添加细胞完成");
//            isAddCell=false;
//            addCellDF=null;
//        }else if(isAddViruses){
//            showDialogMessage("添加病毒完成");
//            isAddViruses=false;
//            addVirusesDF=null;
//        }
    }

    @Override
    public void onRequestEnvironmentLog(EnvironmentLog data) {
        showToast("已发送环境信息");
    }

    @Override
    public void sampleStart() {
        isSampling = true;
//        if (presenter.isPumpStoped(PeristalticPumpBO.PeristalticPump_circulating)) {
//            if(sampleDF!=null) {
//                sampleDF.startSampleOK();
//            }
//        } else {
//            if (presenter.isPumpRunned(PeristalticPumpBO.PeristalticPump_circulating)) {
//                isCircleNeedResumeAfterSample = true;
//                presenter.pausePeristalticPump(PeristalticPumpBO.PeristalticPump_circulating);
//            }
//        }
        if (presenter.isReadyForSample()) {
            if (sampleDF != null) {
                sampleDF.startSampleOK();
            }
        } else {
            //打开循环泵
            if (CirculatingPumpController.getInstance().getSpeed() == 0) {
                presenter.openPumpTask(PeristalticPumpBO.PeristalticPump_circulating, ParamsPreferences.getInstance().getCirculatingPumpSpeed(), ParamsPreferences.getInstance().getCirculatingPumpDirection(), null);
            }
        }
        showToast("开始取样");
    }

    @Override
    public void sampleFinish() {
        isSampling = false;
//        if (isCircleNeedResumeAfterSample) {
//            presenter.resumePeristalticPump(PeristalticPumpBO.PeristalticPump_circulating);
//        }sad
        showToast("取样完成");
        setCornerIndex(btnSample, 1);
        showCornerIndex(btnSample, getString(R.string.sampling), (Integer) btnSample.getTag());
    }

    @Override
    public void saveSampleData(Sample sample) {
        presenter.saveSampleData(sample);
        showToast("保存取样信息成功");
        //流程记录
        Operation operation = new Operation();
        operation.setName(Operation.Operate_Sample);
        operation.setDateTime(new Date());
        operation.setOperator(CartApplication.getInstance().getOperator());
//        operation.setData(sample.getCellAmount()+"ml");
        operation.setData(sample.getMainTankCellFluid() + "ml");
        presenter.saveOperation(operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());
    }

    @Override
    public void showDialogMessage(String msg) {
        if (fragmentManager == null) {
            return;
        }
        DialogFragmentHelper.showMessageDialog(this, null, msg);
    }

    @Override
    public void onNumberMax(String number, EditText editText) {
        initPopWindowIfNeed(number);
        if (rockPop.getPopupWindow().isShowing() && editText == oldEditText) {
            return;
        }
        rockPop.show(editText);
        popDisposable = Observable.interval(1, TimeUnit.SECONDS)
                .take(2)
                .subscribeOn(Schedulers.newThread())
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        return 1 - aLong.intValue();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer <= 0) {
                            rockPop.dismiss();
                        }
                    }
                });
        oldEditText = editText;
    }

    private void initPopWindowIfNeed(String max) {
        if (rockPop == null) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.rock_popup, null, false);
            TextView textView = contentView.findViewById(R.id.textView);
            textView.setText("最大值" + max);
            rockPop = new RockPop.PopupWindowBuilder(this)
                    .setView(contentView)
                    .setFocusable(false)
                    .setOutsideTouchable(false)
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            if (popDisposable.isDisposed()) {
                                popDisposable.dispose();
                            }
                        }
                    })
                    .setDirection(RockPop.DIRECTION_TOP)
                    .create();
        } else {
            ((TextView) rockPop.getPopupWindow().getContentView().findViewById(R.id.textView)).setText("最大值" + max);
        }
    }

    @Override
    public void onLiquidFluidIntake(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_FluidIntake);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.fluidIntake(amount, speed, LiquidLoopTask.Liquid_medium, operator, date, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());
        fluidIntakeLoading.setVisibility(View.VISIBLE);
        setCornerIndex(btn_fluidIntake, 1);
        showCornerIndex(btn_fluidIntake, getString(R.string.fluidIntake), (Integer) btn_fluidIntake.getTag());
    }

    @Override
    public void onLiquidDiacharge(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_Discharge);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.discharge(amount, speed, operator, date, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());
        dischargeLoading.setVisibility(View.VISIBLE);
        setCornerIndex(btn_discharge, 1);
        showCornerIndex(btn_discharge, getString(R.string.discharge), (Integer) btn_discharge.getTag());
    }

    @Override
    public void onLiquidChange(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_ChangeLiquid);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.changeLiquid(amount, speed, speed, LiquidLoopTask.Liquid_medium, operation);
        changeLiquidLoading.setVisibility(View.VISIBLE);
        presenter.requestOperationLog(operation.getName(), operation.getData());
    }

    @Override
    public void onLiquidCollect(int amount, int speed, String collectName, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_Collect);
        operation.setData(collectName + amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.collect(amount, speed, operator, date, operation, collectName);
        presenter.requestOperationLog(operation.getName(), operation.getData());
        collectLoading.setVisibility(View.VISIBLE);
        setCornerIndex(btn_collect, 1);
        showCornerIndex(btn_collect, getString(R.string.collect), (Integer) btn_collect.getTag());
    }

    @Override
    public void onAddCell(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_AddCell);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.fluidIntake(amount, speed, LiquidLoopTask.Liquid_cell, operator, date, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());
    }

    @Override
    public void onAddViruses(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_AddViruses);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.fluidIntake(amount, speed, LiquidLoopTask.Liquid_viruses, operator, date, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());

        setCornerIndex(btn_add_viruses, 1);
        showCornerIndex(btn_add_viruses, getString(R.string.addViruses), (Integer) btn_add_viruses.getTag());
    }

    @Override
    public void onAddCryoprotectant(int amount, int speed, String operator, Date date) {
        Operation operation = new Operation();
        operation.setDateTime(date);
        operation.setName(Operation.Operate_AddCryoprotectant);
        operation.setData(amount + "ml");
        operation.setOperator(operator);

        presenter.stopAllTask();
        presenter.fluidIntake(amount, speed, LiquidLoopTask.Liquid_cryoprotectant, operator, date, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());
        addCryoprotectantLoading.setVisibility(View.VISIBLE);
//        presenter.fluidIntake(amount, speed, LiquidLoopTask.Liquid_cryoprotectant, operation);

        setCornerIndex(addCryoprotectant, 1);
        showCornerIndex(addCryoprotectant, getString(R.string.addCryoprotectant), (Integer) addCryoprotectant.getTag());
    }

    private Disposable startProgressBar(final ProgressBar progressBar) {
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(progressBar.getMax())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                })
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        //aLong从0开始，所以+1
                        return aLong.intValue() + 1;
                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d(TAG, "start max:" + progressBar.getMax() + " progress:" + integer);
//                        showToast("start max:"+progressBar.getMax()+" progress:"+integer);
                        progressBar.setProgress(integer);
                        if (progressBar.getMax() == integer) {
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private Disposable resumeProgressBar(final ProgressBar progressBar) {
        //恢复点
        final int resumePoint = progressBar.getProgress();
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(progressBar.getMax() - progressBar.getProgress())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                })
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        //aLong从0开始，所以+1
                        return resumePoint + aLong.intValue() + 1;
                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d(TAG, "resume max:" + progressBar.getMax() + " progress:" + integer);
//                        showToast("resume max:"+progressBar.getMax()+" progress:"+integer);
                        progressBar.setProgress(integer);
                        if (progressBar.getMax() == integer) {
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void pauseProgressBar(Disposable disposable) {
        if (disposable != null) {
            disposable.dispose();
        }
    }

    private void setProgressMax(ProgressBar progressBar, int max) {
        progressBar.setMax(max);
    }

    private void adjustProgressBar(ProgressBar progressBar, int increase) {
        progressBar.setMax(progressBar.getMax() + increase);
    }

    private void stopProgressBar(Disposable disposable, ProgressBar progressBar) {
        if (disposable != null) {
            disposable.dispose();
        }
        progressBar.setVisibility(View.GONE);
        progressBar.setProgress(0);
        progressBar.setMax(0);
    }

    @Override
    public void startFluidInputProgressBar() {
        //已经开始了，就不能再次开始
        if (fluidIntakDisposable != null && !fluidIntakDisposable.isDisposed()) {
            return;
        }
        fluidIntakDisposable = startProgressBar(progressBar1);
    }

    @Override
    public void pauseFluidInputProgressBar() {
        pauseProgressBar(fluidIntakDisposable);
    }

    @Override
    public void resumeFluidInputProgressBar() {
        if (fluidIntakDisposable != null && !fluidIntakDisposable.isDisposed()) {
            return;
        }
        fluidIntakDisposable = resumeProgressBar(progressBar1);
    }

    @Override
    public void setFluidInputProgressBar(int max) {
        setProgressMax(progressBar1, max);
    }

    @Override
    public void adjustFluidInputProgressBar(int increase) {
        adjustProgressBar(progressBar1, increase);
        //调整了最大值后重新开始画进度条
        pauseFluidInputProgressBar();
        resumeFluidInputProgressBar();
    }

    @Override
    public void stopFluidInputProgressBar() {
        stopProgressBar(fluidIntakDisposable, progressBar1);
    }

    @Override
    public void startDischargeProgressBar() {
        if (dischargeDisposable != null && !dischargeDisposable.isDisposed()) {
            return;
        }
        dischargeDisposable = startProgressBar(progressBar2);
    }

    @Override
    public void pauseDischargeProgressBar() {
        pauseProgressBar(dischargeDisposable);
    }

    @Override
    public void resumeDischargeProgressBar() {
        if (dischargeDisposable != null && !dischargeDisposable.isDisposed()) {
            return;
        }
        dischargeDisposable = resumeProgressBar(progressBar2);
    }

    @Override
    public void setDischargeProgressBar(int max) {
        setProgressMax(progressBar2, max);
    }

    @Override
    public void adjustDischargeProgressBar(int increase) {
        adjustProgressBar(progressBar2, increase);
        pauseDischargeProgressBar();
        resumeDischargeProgressBar();
    }

    @Override
    public void stoptDischargeProgressBar() {
        stopProgressBar(dischargeDisposable, progressBar2);
    }

    @Override
    public void startCollectProgressBar() {
        if (collectDisposable != null && !collectDisposable.isDisposed()) {
            return;
        }
        collectDisposable = startProgressBar(progressBar3);
    }

    @Override
    public void pauseCollectProgressBar() {
        pauseProgressBar(collectDisposable);
    }

    @Override
    public void resumeCollectProgressBar() {
        if (collectDisposable != null && !collectDisposable.isDisposed()) {
            return;
        }
        collectDisposable = resumeProgressBar(progressBar3);
    }

    @Override
    public void setCollectProgressBar(int max) {
        setProgressMax(progressBar3, max);
    }

    @Override
    public void adjustCollectProgressBar(int increase) {
        adjustProgressBar(progressBar3, increase);
        pauseCollectProgressBar();
        resumeCollectProgressBar();
    }

    @Override
    public void stopCollectProgressBar() {
        stopProgressBar(collectDisposable, progressBar3);
    }

    @Override
    public void startChangeLiquidProgressBar() {
        if (changeLiquidDisposable != null && !changeLiquidDisposable.isDisposed()) {
            return;
        }
        changeLiquidDisposable = startProgressBar(progressBar4);
    }

    @Override
    public void pauseChangeLiquidProgressBar() {
        pauseProgressBar(changeLiquidDisposable);
    }

    @Override
    public void resumeChangeLiquidProgressBar() {
        if (changeLiquidDisposable != null && !changeLiquidDisposable.isDisposed()) {
            return;
        }
        changeLiquidDisposable = resumeProgressBar(progressBar4);
    }

    @Override
    public void setChangeLiquidProgressBar(int max) {
        setProgressMax(progressBar4, max);
    }

    @Override
    public void adjustChangeLiquidProgressBar(int increase) {
        adjustProgressBar(progressBar4, increase);
        pauseChangeLiquidProgressBar();
        resumeChangeLiquidProgressBar();
    }

    @Override
    public void stopChangeLiquidProgressBar() {
        stopProgressBar(changeLiquidDisposable, progressBar4);
    }

    //清洗管路和换液使用同一个进度条
    @Override
    public void startCleanPipeProgressBar() {
        if (cleanPipeDisposable != null && !cleanPipeDisposable.isDisposed()) {
            return;
        }
        cleanPipeDisposable = startProgressBar(progressBar4);
    }

    @Override
    public void pauseCleanPipeProgressBar() {
        pauseProgressBar(cleanPipeDisposable);
    }

    @Override
    public void resumeCleanPipeProgressBar() {
        if (cleanPipeDisposable != null && !cleanPipeDisposable.isDisposed()) {
            return;
        }
        cleanPipeDisposable = resumeProgressBar(progressBar4);
    }

    @Override
    public void setCleanPipeProgressBar(int max) {
        setProgressMax(progressBar4, max);
    }

    @Override
    public void adjustCleanPipeProgressBar(int increase) {
        adjustProgressBar(progressBar4, increase);
        pauseCleanPipeProgressBar();
        resumeCleanPipeProgressBar();
    }

    @Override
    public void stopCleanPipeProgressBar() {
        stopProgressBar(cleanPipeDisposable, progressBar4);
    }

    @Override
    public void startAddCell(int amount, String operator, Date startDate) {
        isAddCell = true;
        Operation operation = new Operation();
        operation.setDateTime(startDate);
        operation.setName(Operation.Operate_AddCell);
        operation.setData(amount + "ml");
        operation.setOperator(operator);
        presenter.fluidIntake(amount, ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), LiquidLoopTask.Liquid_cell, operator, startDate, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());

        setCornerIndex(btn_add_cell, 1);
        showCornerIndex(btn_add_cell, getString(R.string.addCell), (Integer) btn_add_cell.getTag());
        if (addCellDF != null) {
            addCellDF.startAddSucc();
        }
    }

    @Override
    public void scourAfterAddViruses() {
        presenter.scourAfterInjection();
    }

    @Override
    public void startAddViruses(int amount, String operator, Date startDate) {
        isAddViruses = true;
        Operation operation = new Operation();
        operation.setDateTime(startDate);
        operation.setName(Operation.Operate_AddViruses);
        operation.setData(amount + "ml");
        operation.setOperator(operator);
        presenter.fluidIntake(amount, ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), LiquidLoopTask.Liquid_viruses, operator, startDate, operation);
        presenter.requestOperationLog(operation.getName(), operation.getData());

        setCornerIndex(btn_add_viruses, 1);
        showCornerIndex(btn_add_viruses, getString(R.string.addViruses), (Integer) btn_add_viruses.getTag());
        if (addVirusesDF != null) {
            addVirusesDF.startAddSucc();
        }
    }

    @Override
    public void scourAfterAddCell() {
        presenter.scourAfterInjection();
    }

    @Override
    public void onTerminateLiquidFluidIntake() {
        presenter.terminateFluidIntake();
    }

    @Override
    public void onTerminateLiquidDiacharge() {
        presenter.terminateDischarge();
    }

    @Override
    public void onTerminateLiquidChange() {
        presenter.terminateChangeLiquid();
    }

    @Override
    public void onTerminateLiquidCollect() {
        presenter.terminateCollect();
    }

    @Override
    public void onTerminateAddCell() {
        presenter.terminateFluidIntake();
    }

    @Override
    public void onTerminateAddViruses() {
        presenter.terminateFluidIntake();
    }

    @Override
    public void onTerminateAddCryoprotectant() {
        presenter.terminateFluidIntake();
    }
}
